jQuery: Global AJAX Events for Start, Stop, Complete, or Error jQuery: Global AJAX Events for Start, Stop, Complete, or Error

When your website contains a lot of AJAX requests using jQuery template and you want to add a global event at the start or finish of the AJAX request, e.g. add a spinning icon, or handle all AJAX errors in a particular fashion.

The jQuery library provides multiple events for ajax event handlers. This article will focus on ajaxStart and ajaxError.


These events are a great way to easily add uniformity to how you handle AJAX requests. For example, perhaps you have a very busy website that on occasion an AJAX request doesn't complete and an error is returned. When there is an error, you could show a standard error dialog asking the user to try again.

Configuring ajaxError


$(document).ajaxError(function() {
$("#error").show();
});

Configuring ajaxStart

Or if you want to always show a loading element when the ajax request starts with a Javascript event and hide it when it's done you could do the following:


$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});

If you want to get more information about the AJAX request, you could update the above calls to pass a variable in the function:


$(document).ajaxStart(function(e) {
$("#loading").show();
});
$(document).ajaxStop(function(e) {
$("#loading").hide();
});

Then you can use the variable e to access some of the properties. For example: console.log(e.currentTarget.activeElement); Will tell you what element made the AJAX request. Inside of Firebug if you perform a console.log(e); you can see all of the properties available of that object.

Published on Feb 18, 2019

Tags: AJAX | JavaScript | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.