jQuery and Ajax - J Query

Problem
You want to make a request to the server for some additional data without leaving the page the visitor is currently on.

Solution

Here’s a simple Ajax request:

Discussion

At the core of jQuery’s Ajax architecture is the jQuery.ajax() method. This provides the basis of all browsers to server requests and responses. So, let’s look at this in a little more detail. To initiate a request to the server, a settings object that contains parameters for the request is passed to the $.ajax method. A vast number of options are available, with the most common options of a request being type, url, complete, dataType, error, and success:

The first option that needs to be addressed when starting an Ajax request is the type of HTTP request you’re going to make to the server, which in the majority of cases will be either a GET or POST type:

Next we’ll look at the URL and dataType options. URL is fairly self-explanatory with the following interactions worth noting. When setting the cache option to false, jQuery will append a get variable of _=<random number>(for example /server-ajax-gateway?_=6273551235126), which is used to prevent the browser, proxies, and servers from sending a cached response. Finally, the dataType option specifies the data format that is the expected response from the server. For example, if you’re expecting the server to return XML, then a value of xml would be appropriate:

The next two options that we define are two callback methods, one called error and the other called success. They function as they are appropriately titled, with error being called when there is an error with the request and success being called with a successful response (determined if a server response type of 200 is returned). The other common option mentioned is the complete option, which defines a callback to execute upon after either success or error of the response:

Once the settings have been defined, we can go ahead and execute our request:

We can also set our options inline:

Our final solution requests the file hello-ajax.html and appends the contents (html) to the <body> element upon the return of a successful request. If the request fails, the error method is triggered instead, alerting the user with a message:


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

J Query Topics