I have a VERY simple jQuery Ajax call (below). The Ajax call executes and I can see in the Firebug Net panel that the server returned 200 OK and returned a string "OK" as it should. However, the done and fail functions do not fire! Very frustrating!
(The "before" and "after" alerts DO fire. )
For simplicity (and as a debugging technique) I have stripped this down to it's most bare skeleton but still the handlers won't fire. What am I not seeing here?
postUrl= "/mod/users/check_email/";
dataToPost= { email: "[email protected]" };
alert("before");
$.ajax
({
type: "POST",
url: postUrl,
data: dataToPost,
done: function()
{
alert("Success.");
},
fail: function()
{
alert("Sorry. Server unavailable. ");
},
}); // end Ajax call
alert("after");
The ajaxComplete() method specifies a function to be run when an AJAX request completes. Note: As of jQuery version 1.8, this method should only be attached to document. Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
success is the callback that is invoked when the request is successful and is part of the $. ajax call. done is actually part of the jqXHR object returned by $. ajax() , and replaces success in jQuery 1.8.
The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.
You need to chain the done()
and fail()
functions, they are not part of the options object used in $.ajax
:
$.ajax({
type: "POST",
url : postUrl,
data: dataToPost
}).done(function() {
alert("Success.");
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
Also, as ajax is asynchronous, don't be suprised if the "after" alert comes before the "success" alert.
success
and error
callbacks can be used in that way. For done
and fail
, you need to do :
$.ajax({
type: "POST",
url: postUrl,
data: dataToPost,
}).done(function() {
alert("Success.");
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
Or :
$.ajax({
type: "POST",
url: postUrl,
data: dataToPost,
success: function() {
//code here
}
});
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