Introduction to Ajax with jQuery

The term Ajax is an acronym containing a reference to the technologies that are covered under it. , but for now, note that Ajax stands for Asynchronous JavaScript and XML. Although more than just JavaScript and XML are involved in Ajax, the name was coined to contain only the two technologies mentioned. Quoting Wikipedia,

The term “Ajax” was publicly stated on 18 February 2005 by Jesse James Garrett in an article titled “Ajax: A New Approach to Web Applications,” based on techniques used on Google pages.

Now, let’s consider Ajax’s functional origins and the technologies from which it is composed.

How Did Ajax Originate?

Ajax was not a completely new technology as such. It was a grouping of already-known technologies harnessed to attain some objective. When we say “already-known,” we mean to say that none of the technologies in Ajax was new. They were already in use, to a rather considerable degree, in creating and maintaining web-based applications across the world. The engineers at Google were working tirelessly to create an e-mail system to be used in a web browser in which the end user would not have to reload an entire page to fetch a new e-mail. It was in 2004 that this hard work gave to the world Gmail, a fully cross-browser compliant application built using Ajax. Google extended its efforts and came up with another product that used Ajax—Google Maps—just about a year later, in 2005.

We would like to emphasize here that it was not Google that started using Ajax; it was Google that popularized it. There were attempts all around the world to attain something similar. Some approaches included writing some scripts inside the web page, so that even after the web page was downloaded, these scripts were able to pull more data from the server. This mechanism was available in Netscape, and this feature was known as LiveScript. The engineers at Netscape continued their hard work, and they enabled a feature to render some content written in XML, making it look like a regular web page. People at Microsoft were watching all this closely, and they added a method to the JavaScript implementation in their browser: the IE5. The name of the method was XMLHttpRequest. Using this method, the JavaScript rendered inside the web page could communicate to the web server and obtain data from the server. When Microsoft did this, Mozilla was the next to implement this method, in their JavaScript implementation in Firefox. It was after these giants moved ahead to secure this functionality that it began to garner attention, and Google made the maximum use of it. There was an e-commerce setup, with a web site located at www.kayak.com, which was another large-scale implementation of the phenomenon.

Image Tip  For an in-depth look into the history of Ajax, see www.aaronsw.com/weblog/ajaxhistory.

The Technologies That Make Up Ajax

As we already stated at the beginning of this chapter, Ajax is not a technology in itself; it is a group of already fully developed technologies. Speaking in very broad terms, the technologies used in Ajax are combined HTML/CSS and JavaScript. Let’s look into the share each of the technologies mentioned possesses in Ajax.

Starting with the HTML/CSS combination, we would like to state that all web applications that are to be executed on the web browser need HTML to render the content to the end user. Thus, all the HTTP responses that are sent back to the web browser by the web server are interpreted by the web browser as HTML tags and codes. Because Ajax can be used to exchange data from the server, there needs to be HTML, and since the HTML needs to be presented in some useful format, CSS is used to decorate the (probably) ugly bits and pieces that are used to create the building blocks of the user interface (UI) related to the HTTP request sent and the HTTP response obtained thereby.

Another technology involved in Ajax is JavaScript, which plays a major role in Ajax. In the presentation component, JavaScript is used to provide the capability to perform DOM manipulation in order to “adjust” the data that has been received as a part of the Ajax response by the web server. At the data exchange layer, JavaScript makes provisions to have the data sent and received as JSON or plain text. In short, there is a method that we mentioned a while ago, XMLHttpRequest, which makes up for the asynchronous behavior in Ajax.

Considering it all together, you might want to ask a simple question: If it offers nothing new, why has the term Ajax become jargon? We will take pains to answer this simple question in a not-so-simple way. We suggest you pay careful attention to what we are about to say, because while the statements will answer your question, they will make an assertion regarding the advantages that are served by this jargon. The technologies were already there but were not used as a group, because no one in the industry bothered using them until someone found a use for them. Because a use was found, others began to look for ways to take advantage of this discovery. Thus, people started thinking of the possibility of eliminating the difference in the user experience between a desktop-based application and a web-based application.

The traditional user experience for a web-based application was such that for every requested change in the data, the entire page was reloaded. This is to say that the communication between the web browser and the web server was synchronous, in the sense that the server would resend all data synchronously to the web browser, which meant that the entire web page would be refreshed (by getting a fresh copy of the data on the server). With the use of Ajax, the communication could be asynchronous, because the same web page could make separate XMLHttpRequest communications to (the same or different) web server(s) without their interfering with each other.

Ajax Using jQuery

Having said enough about the technology, let us move ahead and carry out the task that pertains to the subject of this book. We covered what Ajax is and what is inside it, now it is time for us to establish the relationship between Ajax and jQuery. Most readers may wonder how the two entities are related to each other. For the sake of clarification, we will make an assertion and, later on, explain that assertion: Ajax is a concept encapsulating a number of well-known and already used technologies, and jQuery is a framework written in a scripting language—JavaScript. Simply stated, you can use an Ajax methodology or technique (whichever name you prefer) using a framework known as jQuery. How is discussed in the sections and the examples that follow.

The Nuts and Bolts of Ajax in JavaScript

Because it has been our approach to begin the discussion with the basics, and because we have already explained the basics of Ajax, we will take up the JavaScript approach to Ajax. While this might seem a topic off-topic, it is not. It will give you some insight into the working of the jQuery framework in the current context. Consider the following simple use case. There is a page containing some text, and there is a need to pull that data into some other section inside a web page. All this has to be done asynchronously. So, because we are front-end web developers, we will resort to using JavaScript as a first line of defense. We propose using its workhorse method—the XMLHttpRequest available with the JavaScript implementation of (new) browsers. We’ll start by informing you about the essential details related to the XMLHttpRequest object.

The XMLHttpRequest encapsulates certain methods that are essential to complete the asynchronous functionality. Following, we list the necessary methods and members with a brief explanation related to what the methods/members are and what they do:

  • open(): This method opens a new HTTP connection to the web server. In simple terms, this method initiates a new HTTP request.
  • send(): This method sends the HTTP request to the web server on the open connection.
  • readyState: The state of the HTTP request at any instant of time. The value starts from 0 when it is opened and has not been called. It turns to a 1 immediately after the connection has been opened (by calling the open() method). Then it attains a value of 2, when the server has presented the HTTP headers. The next value attained by the readyState is 3, which means that the data is being downloaded onto the client. The value which is attained after 3 is 4, which represents the state of the request when completed. You mostly would be interested in using this value to perform some desired action.
  • onreadystatechange: You have to program the actual asynchronous functionality inside this function. That is to say that once you send an HTTP request to the server, the value of another property (readyState) encapsulated by the XMLHttpRequest changes. So, this onreadystatechange is defined as a function containing the activity to be performed once the readyState changes.
  • status: The HTTP response code as returned from the server. The value that is of interest to us is 200. This value stands for success. You will most often look for an opportunity to have this status code returned from the server, to perform any action.
  • responseText: This is the property exhibited by the XMLHttpRequest method (or class) to represent the text as returned from the server.

To sum up, we propose a way for you to look into the way JavaScript performs an asynchronous request. We begin with the HTML part, which is rather simple, as follows:

<!DOCTYPE html>
<html>
   <head>
       <title>:: Playing with Ajax ::</title>
   </head>
   <body>
       <span id="ajax-initiator" onclick="getData()">Click here to get data from an external
           source</span>
       <div id="ajax-data"></div>
   </body>
</html>

The corresponding JavaScript code will look as follows:

function getData(){
    var ajax = new XMLHttpRequest();
    ajax.open('GET', 'ajax-data.html');

    ajax.onreadystatechange = function(){
        if(ajax.readyState == 4 && ajax.status ==200){
            document.getElementById('ajax-data').innerHTML = ajax.responseText;
        }
    }

    ajax.send(null);
}

So, for a quick explanation, a new connection is set up to the HTML file (which is expected to contain some data), and once the server returns the value, this value is inserted into a div (which we had already put in with the ID ajax-data).

The jQuery Approach

We have been saying that jQuery is a framework written in JavaScript. The task of any framework is to ease the load of performing common tasks by providing methods/functions (whichever term you prefer) intended to solve common problems. Considering asynchronous requests as one such problem, the jQuery framework does not let you down. There are a number of ways in which the framework lets you work on asynchronous programming. Before we take up the methods provided in jQuery, we take this opportunity to state that there is a “mother” method, on the one hand, and there are wrapper methods that make available the functionality of this mother method to solve common problems. Trust us, most of the time, you will find the wrapper methods better than the mother method. This statement can be taken to be an extension of the objective of this book: JavaScript is the mother language, and jQuery is a wrapper to the jQuery methods, and people find jQuery more useful most of the time.

Image Note  The .ajax() method is also defined as a “low-level” Ajax interface.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares