I have this code:
$( document ).ajaxComplete(function( event, xhr, settings ) {
console.log('test');
});
I opened the chrome network tab and I can see only one entry (status 200).
But the console displays:
(28) test
Why is it executed this often?
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.
The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .
jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
The ajaxComplete
triggers when any AJAX
request is completed, even if it's successfull or not.
The 200 status code
means that your request has gone right, but, as you can read in jQuery docs that callback will fire every time an AJAX
request has finished.
So, you could check what URL is your request redirecting to and handle only the ones that you need.
Anyway ( just a side note ) I will use the built-in AJAX
callback function complete
, something like this:
$.ajax({
url: url,
data: { data },
complete:function(){
console.log('test');
}
});
You can check urls of these ajax'es, and handle only needed:
$( document ).ajaxComplete(function( event, xhr, settings ) {
console.log('Ajax request completed for: ' + settings.url);
if ( settings.url === "ajax/test.html" ) {
$( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
xhr.responseText );
}
});
Bind it only once when document ready:
$(function() {
$( document ).ajaxComplete(function( event, xhr, settings ) {
console.log('Ajax request completed for: ' + settings.url);
if ( settings.url === "ajax/test.html" ) {
$( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
xhr.responseText );
}
});
});
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