Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global callback for Ajax calls in JQuery

Is it possible to create and attach a callback which would get called whenever an ajax request completes regardless of whether the call was made using $.ajax, $.post, load or any other function?

EDIT:

The solution given by Nakul (using ajaxSuccess global event) is almost perfect. However I have a problem when using this with the load function. The ajaxSuccess event is raised after the request has completed but before any DOM manipulation. I would like to execute some code after the DOM has been modified. My temporary solution is to use setTimeout and wait for a couple of milliseconds but I don't think it'd be reliable enough for me.

So another question is: how can you execute code after the DOM has been manipulated by the load function?

EDIT 2:

I've managed to solve the second issue by using ajaxComplete event instead of ajaxSuccess.

like image 598
Marek Stój Avatar asked Jan 09 '10 09:01

Marek Stój


People also ask

What is callback jQuery AJAX?

jQuery - ajaxSuccess( callback ) Method The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

What is global AJAX?

These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery. ajaxSetup() is true , which it is by default.

Which global event is triggered if an AJAX request is started and no other AJAX requests are currently running?

The ajaxStart and ajaxStop events are events that relate to all Ajax requests together. This event is triggered if an Ajax request is started and no other Ajax requests are currently running.

Which global event is triggered if there are no more AJAX request being processed?

ajaxStop GlobalEvent This global event is triggered if there are no more Ajax requests being processed.


2 Answers

You can use ajaxSuccess More here: http://www.slideshare.net/wildan.m/jquery-talk-to-server-with-ajax (after slide 47)

like image 85
Nakul Avatar answered Oct 02 '22 21:10

Nakul


Use the ajaxSuccess and maybe you want to run the code when you click a link?

HTML:

<a href="javascript:void(0);" class="runCode">Run code</a>

JS:

$(function() { // same as dom loaded
    $('a.runCode').click(function() {
        alert('whatever you want to do here');
    });
});
like image 31
Mickel Avatar answered Oct 02 '22 20:10

Mickel