phpjssql
phpjssql

Reputation: 501

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?

Upvotes: 6

Views: 593

Answers (2)

Serhii Kozachenko
Serhii Kozachenko

Reputation: 1401

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 );
      }
    });
});

Upvotes: 1

CapitanFindus
CapitanFindus

Reputation: 1526

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'); 
    }
});

Upvotes: 1

Related Questions