Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AjaxComplete called to often

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?

like image 800
phpjssql Avatar asked Sep 21 '15 12:09

phpjssql


People also ask

What is ajaxComplete?

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.

What is URL in AJAX call?

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 .

How do you check if all AJAX calls are completed?

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.


2 Answers

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'); 
    }
});
like image 191
CapitanFindus Avatar answered Oct 03 '22 16:10

CapitanFindus


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 );
      }
    });
});
like image 43
Sergiy Kozachenko Avatar answered Oct 03 '22 16:10

Sergiy Kozachenko