Run the function if you have ajax get / post running
As my title states, I need to run the function if any ajax get / post is fired.
I tried to use
$(document).ajaxStart(function () {
console.log('a');
});
$(document).ajaxComplete(function () {
console.log('c');
});
but it only starts the first time.
Later, it does not register anything. What am I doing wrong?
I need to do this in chrome extension and google image search page, so after 100 images it fires an ajax function to get more image data and show on page.
source to share
You probably want it to work even if no AJAX requests are made with jQuery with a method like How do I check if HTTP requests are open in the browser?
(function() {
var oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
console.log('Request went out', arguments);
oldOpen.call(this, method, url, async, user, pass);
}
})();
source to share
The ajax method itself can accept functions in beforeSend
and complete
.
.ajax({
// the rest of your parameters
complete: function(data) {
// do something
}
});
If you don't want to specify them on a request basis, you can do so with the `.ajaxSetup 'function, which overrides the default values.
.ajaxSetup({
beforeSend: function() {
// custom logic
},
complete: function() {
// custom logic
}
});
source to share