Is it that
success()
returns earlier thancomplete()
?
Yes; the AJAX success()
method runs before the complete()
method.
Below is a diagram illustrating the process flow:
It is important to note that
The success()
(Local Event) is only called if the request was successful (no errors from the server, no errors with the data).
On the other hand, the complete()
(Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
... more details on AJAX Events here.
complete
executes after either the success
or error
callback were executed.
Maybe you should check the second parameter complete
offers too. It's a String holding the type of success the ajaxCall had.
The different callbacks are described a little more in detail here jQuery.ajax( options )
I guess you missed the fact that the complete
and the success
function (I know inconsistent API) get different data passed in. success
gets only the data, complete
gets the whole XMLHttpRequest
object. Of course there is no responseText
property on the data string.
So if you replace complete
with success
you also have to replace data.responseText
with data
only.
success
The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.
complete
The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
If you need to have access to the whole XMLHttpRequest
object in the success callback I suggest trying this.
var myXHR = $.ajax({
...
success: function(data, status) {
...do whatever with myXHR; e.g. myXHR.responseText...
},
...
});
"complete" executes when the ajax call is finished. "success" executes when the ajax call finishes with a successful response code.
Well, speaking from quarantine, the complete()
in $.ajax is like finally
in try catch block.
If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.
Same goes for complete()
in $.ajax, whether you get success()
response or error()
the complete()
function always will be called once the execution has been done.
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