GibboK
GibboK

Reputation: 73928

How to manully trigger an ajaxComplete event

Using Jquery I need to trigger a ajaxComplete event.

At the moment I'm using this code with no success

$.getJSON(assetUrl, function (data) {
...
    $.trigger("ajaxComplete");

With Error:

TypeError: 'undefined' is not a function (evaluating '$.trigger("ajaxComplete")')

Any idea what I'm doing wrong? Thanks

Upvotes: 0

Views: 3073

Answers (3)

Inc33
Inc33

Reputation: 1901

If anybody else is looking at this, the correct way to manually trigger ajaxComplete is $(document).trigger('ajaxComplete', [xhr, settings]);

It's probably important to pass the xhr object to the ajaxComplete trigger event, as the event handler might need it.

However, you only need this, if you're not making your requests through jquery, since jquery handles this automatically for you.

Upvotes: 0

Wes
Wes

Reputation: 785

You can define a global jQuery ajaxComplete (and ajaxError) function that will run on document ready and after every completed ajax request. You can define the ajaxComplete function on the intial page load (or whenever really) like this:

$(function(){
      $(document).ajaxComplete(function(){

        // on complete code

      }).ajaxError(function(){

        // on error code

      });
});

To call this event handler at any time, just execute the following:

$(document).triggerHandler('ajaxComplete');

Upvotes: 3

Bergi
Bergi

Reputation: 664569

The ajaxCompleted event is fired on the DOM, and you will need to call the trigger method on a jQuery wrapper element: $(document).trigger(...), for example.

There is not static function "trigger" on the jQuery object (that's what the error message is telling you), you might use $.event.trigger - though I fear that's internal.

However, you won't need to do it manually; getJSON does trigger the event itself. For aborting a running ajax request, see the abort method of XHR objects.

Upvotes: 3

Related Questions