In one of our previous tutorials Getting Starting with AJAX using JQuery, we went over the basics of using Ajax. What if you wanted more control? Say you wanted to run a function when the AJAX experiences an error? We will go over some more approaches to handling AJAX using JQuery.

The $.ajaxSetup() Method

This Ajax method is a very helpful method. The .ajaxSetup method is used to set default values for future AJAX requests. The proper syntax and usage goes as follows:

This can be very helpful to customize your Ajax request and “debug” certain instances of your project. There are two parameters you can pass, the name (anyone one of the 24 like cache, password etc.) and the value of that category name. Here is an example. Did you know that IE always Caches Ajax requests? So many times when viewing the AJAX on your site, it may be a cached state from your last session? To override this, we would use .ajaxSetup and specify a name and value. Here is our example to get rid of AJAX caching.

The $.getJSON() method

Both the data and success are optional values. As you can see the JSON call is very similar to your standard AJAX call, except for the Success parameter which is will display a status string (“success”, “notmodified”, “error”, “timeout”, or “parsererror”) upon a successful JSON request.

This one is a little more complex but is quite simple. You make the request using .getJSON and mention the http url (demo_ajax_json.js). The function contains some coding the will display the result field of the JSON script and append it after the div field.

The $.ajaxComplete() method

This ajax method is pretty self explanatory but is very useful. This method will run a function once the ajax has been completed, whether or not the ajax call was successful or not.

The $.ajaxSend() method

Use the ajaxSend() method to help pass a function to run when an AJAX requests is about to be sent. This can be very helpful to display a graphic or helpful string of text to notify the user of the ajax progress or update.

The $.ajaxSuccess() method

The ajaxSuccess() method specifies a function to be run when an AJAX request is successfully completed. Using this Ajax method can be helpful to verify or ensure that the AJAX call was sent successfully.

The $.ajaxError() method

The ajaxError() method specifies a function to be run when an AJAX request fails. This method is your go to method to let the user know that their ajax request has failed and is commonly followed by an alert.

AJAX is a great way to to help optimize your site by reducing loading all of your content at once. Think of it as a way to store and pull your files for later use instead of throwing it at the user all at once. For more details and useful AJAX methods, visit W3 Schools JQuery AJAX Methods.