Using Ajax on Your Whole Site - J Query

You have a large web application with Ajax calls occurring throughout the code base and need to define default settings for all requests throughout the application.



When working with larger applications, often there is a common Ajax gateway through which all requests are passed. Using the $.ajaxSetup() method, we can set Ajax request default settings. This would result in an ease of Ajax requests throughout the application such as follows:

A brief side point is that the timeout option takes its value in milliseconds (seconds ×1,000), so a timeout of 6,000 would be six seconds. One thing to consider when setting this value is the extent to which the Internet has grown globally. Some of your visitors or users may be in locations that have a higher latency than you would expect for users within your region. So, don’t set this value too low (for example five seconds). Specifying a higher timeout value such as 30 or 60 seconds will allow users with higher latency connections (such as those using satellite) to still enjoy the benefits of your application.
In the previous example, the request will be a POST to ajax-gateway.php. If an error occurs, it will be handled by the error function as defined in $.ajaxSetup(). It is possible to still override settings for a specific request as follows:

The previous request would be sent to another-url.php instead of ajax-gateway.php.One beneficial feature of jQuery’s Ajax architecture is the global events available such as ajaxComplete, ajaxError, ajaxSend, ajaxStart, ajaxStop, and ajaxSuccess. These events may be set up using the .bind('event', callback) method or the shortcut .event(callback). The following example shows the two methods for binding the callback for the ajaxError event:

Here is a rundown and description of the events that are available as well as the order in which they’re triggered:

Triggered at the start of an Ajax request if no other requests are in progress
Triggered before each individual request is sent
ajaxSuccessor ajaxError
Triggered upon a successful or an unsuccessful request
Triggered every time a request is complete (regardless of whether it was a success or had an error)
Triggered if there are no additional Ajax requests in progress
In the next recipe we will build upon these events in more detail.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics