0

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

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Why would you need to trigger that manually? – Bergi Dec 17 '12 at 13:51
  • I would like to know if it is possible stop AJAX call with a command in the script, so I was thinking to trigger an event... it is possible in this way? Or alternatively is it possible to use some sort of abort method? – GibboK Dec 17 '12 at 13:53
  • 3
    @GibboK `xhr.abort();` makes more sense. Edit in response to your edited comment, see http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery. – Rob W Dec 17 '12 at 13:54
  • It is `jQuery.fn.trigger` and not `jQuery.trigger`... Perhaps : `$("body").trigger(...)`? – Samuel Caillerie Dec 17 '12 at 13:55
  • 1
    Hi this provides the way to abort the request. http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – LPD Dec 17 '12 at 13:57

3 Answers3

3

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.

GibboK
  • 71,848
  • 143
  • 435
  • 658
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

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');
Wes
  • 765
  • 5
  • 9
0

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.

Inc33
  • 1,747
  • 1
  • 20
  • 26