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.
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.
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.
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.
ajaxStop GlobalEvent This global event is triggered if there are no more Ajax requests being processed.
You can use ajaxSuccess More here: http://www.slideshare.net/wildan.m/jquery-talk-to-server-with-ajax (after slide 47)
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');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With