DotNetCurry Logo

Getting started with jQuery $.ajax() – Back to Basics

Posted by: Suprotim Agarwal , on 2/26/2015, in Category jQuery and ASP.NET
Views: 16719
Abstract: A quick look at Ajax and also explore Ajax, the jQuery way.

Ajax stands for Asynchronous JavaScript and XML and is a group of technologies used by a browser to asynchronously send and fetch data from the server. People want websites that feel faster and responsive, almost similar to desktop applications. Sites like Twitter, Facebook, Gmail, Bing Maps etc. have blurred the lines between desktop and website applications and the technology that makes this possible is Ajax. Ajax can breathe life into any user interface.

We’ll be taking a quick look at Ajax in this article, and also explore Ajax, the jQuery way. So please note that this isn’t intended as a complete Ajax tutorial. If you are new to jQuery and jQueryUI, you may want to take a look at Getting started with jQuery and jQuery UI – Back to Basics

The diagram here shows how a normal HTTP request is made VS an Ajax Request:

httpreqvsajax

The first diagram represents a normal HTTP request made by the browser to which the server returns an entire page (including HTML, CSS, JavaScript). The browser on receiving the page, has to remove the current page and reload this entire page to display it to the user. From the time the request is made and the server responds; the user can do nothing but stare at your page while the browser loads the entire page.

The second diagram represents an Ajax request. The browser uses JavaScript to send an XMLHttpRequest (XHR) object to the server. This XHR object (which is a part of Ajax) includes data that tells the server what is being requested. The server then responds with only the data that was requested for. When the server responds with the data, the browser uses JavaScript to receive the data, processes it and updates only a portion of the page that has changed. All this occurs asynchronously in the background without any page reloads; while the user continues working on the other parts of your webpage. This gives the user a more responsive and natural experience.

To understand this better in a real world application, whenever you posted a comment on Facebook, if the entire page had to reload just to show your comment; it would lead to a very slow and unresponsive user experience. Since Facebook uses Ajax, the comment instantly shows up without any page refreshes. With Ajax, your webpage only requests the server for what data it really needs or just the part of a page that needs to change.

Although Jesse James Garrett in the year 2005 is credited with coining the term Ajax; the technology surfaced in 1998, when Microsoft pioneered the ability to perform async requests as an ActiveX control in their Outlook Web Access (OWA) application. Although a few noticed this technology in the OWA application, it was in 1999 when people noticed it when Internet Explorer 5 (IE5) used this XMLHTTP ActiveX control to make async updates. Later browsers like Mozilla, Safari and Opera adopted this technology and created the XMLHttpRequest object, which forms the backbone of every Ajax request.

Why jQuery for Ajax?

Browsers are not entirely consistent with regard to their implementations of the XMLHttpRequest object, but jQuery has its suite of AJAX functions which offer some significant improvements over the native JavaScript AJAX features, as they are a lot consistent and easier to use.

At the heart of applying Ajax with jQuery’s is the $.ajax() function. If you open the jQuery source file, you will find that the $.ajax() functionality is a massive 370+ lines long piece of code and provides easy to use wrapper functions to perform many Ajax operations, including loading text, XML, Script, HTML and JSON data into our web applications.

The method takes the form:

$.ajax({
    type: "GET",
    url: "/someurlhere",
    dataType: "json", // text, html, xml
    //additional settings come here
});

type represents the type of the request (GET or POST) you are making to the server. The default is GET. The url could be local (same domain) or remote (different domain). If the url is on an external domain, we need to treat it differently, which we will see how to do in Recipe 54. The dataType setting sets the type of the data you are expecting back from the server. One thing to note here is that $.ajax() is not called on any element, but on the jQuery object ($) itself.

Since jQuery 1.5, the $.ajax() method returns a new object of the type jqXHR, which is a superset of the XMLHttpRequest and expands it by adding some useful features to support the jQuery Ajax wrapper function. You can use this object to interact with the Ajax request. I personally never use the jqXHR object unless I need to get additional information about the response from a server.

Some jQuery Ajax Wrapper functions are as listed here:

  • load() – loads data from the server directly into the element represented by jQuery object
  • getScript() – loads and immediately executes a script
  • getJSON() – loads data in JSON format
  • get() – sends a generic GET request to the server
  • post() – sends a generic POST request to the server

Handling Callbacks

After the web browser sends off a request to the server using the XMLHttpRequest object, it waits for a response from the server. When the server responds, a callback function handles the server’s response. jQuery Ajax also provides ways of handling callbacks for success and failure.

Prior to jQuery 1.8, you could use success and failure callbacks in the following manner:

$.ajax({
    type: "GET",
    url: "/someurlhere",
    dataType: "json", // text, html, xml
    success: yourSuccessCallback,
    error: yourErrorCallback
});

function yourSuccessCallback(data_returned, status) {
    // code comes here 
}

function yourErrorCallback(request, status, error) {
    // code comes here 
}

As of jQuery 1.8, .success() and .error() are deprecated and replaced with .done() and .fail().

  • .done(response, status, jqXHR) - called when the response from the server is successful
  • .fail(jqXHR, status, error) - called when the response from the server fails or the request times out.
  • .always(response, status, jqXHR) - Always called when a response is received from the server

You can call these functions directly on $.ajax() in the following manner:

$.ajax({
    type: "GET",
    url: "/someurlhere",
    dataType: "json" // text, html, xml
}).done(function () {
    //call is successful
}).fail(function () {
    //call has failed
}).always(function () {
    //always execute despite failure/success
});

However a cleaner approach is to save the returned value of $.ajax() into a variable and then declare the callback functions on that variable. This is possible due to Deferreds which manages callbacks in a much elegant way.

var x = $.ajax({
    type: "GET",
    url: "/someurlhere",
    dataType: "json" // text, html, xml
});

x.done(function () {
    //call is successful
});

x.fail(function () {
    //call has failed
});

x.always(function () {
    //always execute despite failure/success
});

The advantage of this approach is that it is cleaner and you can have multiple .done() and .fail() callbacks defined on the variable.

jQuery Ajax Events at Global Level

If you have a requirement of handling an event on each Ajax request in your application, you can do this globally. jQuery provides methods to create global event handlers. These handlers can be called on events such as initialization or completion for all AJAX requests. Here’s a list of global Ajax event handler registration functions:

  • ajaxStart - when the first AJAX request starts.
  • ajaxSend - before an AJAX request is sent.
  • ajaxStop - when all AJAX requests have completed.
  • ajaxSuccess - AJAX request completes successfully.
  • ajaxComplete - AJAX requests are fully complete.
  • ajaxError - when AJAX requests fail.

Here’s an example to register a global event handler:

$(document).on("ajaxStart", function () {
    // display some message to the user
});

$(document).on("ajaxComplete", function () {
    // display some message to the user
});

If you want to prevent execution of these global event handlers, you can set global options as false in the $.ajax() method:

$.ajax({
....
    global: false;
});

As of jQuery 1.9 onwards, you can only use the document object to call the method handlers for the Ajax global events. In versions prior to 1.9, you could call these method handlers on any element.

XML or JSON

Although ‘x’ in AJAX represents XML, it is a misnomer these days as most applications now use a more lightweight format called JavaScript Object Notation (JSON) to transport data. Ajax has now rather evolved to Ajaj which represents Asynchronous JavaScript and JSON.

As mentioned earlier, JSON is a lightweight format that is used for data interchange. It looks very similar to a JavaScript object. Shown here is an example of JSON:

{
    "firstName": "John",
    "lastName": "Doe",
    "city": "Seattle",
    "transactionCode": [
        "111111111111111111",
        "222222222222222222"
    ]
}

Observe that although JSON looks very similar to a JavaScript object, keys in a JSON object have to have double quotes around them. A JavaScript object does not have this requirement. You can check if your JSON is valid using jsonlint.com

JSON can handle the following datatypes:

  • Numbers
  • Strings
  • Object / Arrays
  • Boolean
  • null

The two main methods to parse JSON is JSON.stringify() that takes a JavaScript object and returns a JSON string, and JSON.parse() that takes a JSON string and parses it to a JavaScript object.

For older browsers that do not support JSON, you can use the JSON 3 script https://github.com/bestiejs/json3 that provides JSON functionality to older browsers.

Check out my next article which talks about fetching JSON data from the server.

JSONP

Cross-domain requests occur when you send AJAX requests to separate servers, from different domains. For security reasons you can’t send an XMLHTTP request to a different domain. There are a couple of ways to work around this like having the webserver act as a proxy to the other server. Alternatively, the second workaround, which is also the most popular one, is JSONP (JSON with Padding) where we use the &jsoncallback=? piece to notify the external website that we want to receive JSONP data. Internally jQuery’s $.getJSON() function treats this request as if the web browser was requesting an external JavaScript file and thus makes the call successful. Check out my next article which talks about fetching JSONP data from the server.

GET or POST

The two most common HTTP methods for sending a request to a server are GET and POST. The main difference between GET and POST is how the data is sent to the server.

GET is used for operations where you are not planning to change any data on the server; you just want to get data from the server. GET requests generally send all of their data in a query string parameter by appending the form field names and values onto the end of the URL.

POST is used for operations where you are planning to change data on the server. A POST request passes parameters as part of the request data. If you are submitting a lot of data to the server, use POST.

jQuery’s get() and post() functions provide simple tools to send data to and retrieve data from a web server.

Take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by K Jayesh on Saturday, May 30, 2015 12:29 AM
Nicely explained article. Very useful for the beginners.
Thanks.