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?
Try this:
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With