Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I debug a jQuery Ajax request?

My code is:

var test = "it isn't working";
var response = $.ajax({
    type: 'GET',
    url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error.
    success: function(){
            test = "it's working";
        },
    error: function(){
            alert("Error detected");
        }
 }).responseText;
alert(test);

I tested the status code and it came out to a 200 and the error function never goes off, but neither does the success function. Like I said in my comment, it isn't a same-origin policy error. It just stays saying "it isn't working". What's going on here?

like image 524
needhelpwithsumajax Avatar asked Aug 09 '11 04:08

needhelpwithsumajax


3 Answers

Try this:

 error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(jqXHR));
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
 }
like image 74
Fernando Fabreti Avatar answered Oct 20 '22 18:10

Fernando Fabreti


Your ajax call is asynchronous. It has not completed yet when your alert at the end runs. Put an actual alert in the success function and you should see your result there.

Remember that making the ajax call just starts the asynchronous ajax call and then the rest of your code continues to run. In the code example you posted, that means your alert(test) call runs right away before the ajax call has completed.

You can ONLY examine the results of the ajax call from within the success handler itself.

var test = "it isn't working";
var response = $.ajax({
    type: 'GET',
    url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error.
    success: function(){
            alert("it's working");   // put this here and you will see it 
                                     // if the ajax call is successful
        },
    error: function(){
            alert("Error detected");
        }
 }).responseText;
like image 22
jfriend00 Avatar answered Oct 20 '22 19:10

jfriend00


To debug these types of things, I find Firebug an indispensable tool. It will show you exactly the response from the server (500 error, 553 error, what have you). You can put break points in your Javascript code and debug it step by step. Firebug works on Firefox.

For IE, you can use the Developer Tools feature which is similar to Firebug, specially on IE9 which seems more mature than previous versions of the Developer Tools for IE7 or IE8.

like image 24
Icarus Avatar answered Oct 20 '22 20:10

Icarus