CodingBison

AJAX blurs the line between desktop applications and webpages. AJAX enables us to request only a certain subset of page or its data from the server while every other information on the page remains intact. This saves a lot of time since we do not have to get the entire page and its data from the sever. Because we do only smaller data transmissions (instead of the entire page, every time), this also means that we are more efficient.

AJAX stands for Asynchronous JavaScript and XML. The Asynchronous means that once the client sends the request, it handles the response as and when it arrives from the server. The client does not wait (or block) for the response and goes on to do the next available task. AJAX runs on top of JavaScript and hence the JavaScript in its name. XML stands for Extensible Markup Language (XML) and is a markup language for representing data. Even though AJAX term contains XML for sending data, it is not mandatory to use XML. In fact, it is common for clients to send AJAX data as plain text, html, or as Java Script Object Notation (JSON).

The AJAX calls run on top of a basic API that is standardized for browsers: XMLHttpRequest or XHR, for short. This API sends request to HTTP server and processes the incoming response asynchronously.

jQuery, being a JavaScript library, provides a set of simple methods for adding AJAX functionality: .load(), .get(), and .post(). So, right off the bat, let us look at their definitions.

 .load(url, dataToSend, callbackFunc(rcvdText, rcvdStatus, rcvdjQueryXHR));    [Added in 1.0]
 $.get(url, dataToSend, callbackFunc(rcvdText, rcvdStatus, rcvdjQueryXHR));    [Added in 1.0]
 $.post(url, dataToSend, callbackFunc(rcvdText, rcvdStatus, rcvdjQueryXHR));   [Added in 1.0]

The .load() method is applied to specific element(s). The other two methods are static methods and do not have to invoked by any specific elements. Please note that, jQuery also has a method by the same name (.load()) that deals with loading of the document -- however, that method is now deprecated and we should avoid using that.

Simply put, these methods interact with server by sending a request to the HTTP server. These request can be of two types: GET and POST. Typically, we use GET method when the request does not change any state on the server and the POST method when the request carries data that can change the state on the server. An important difference between these methods is that the GET method has a built-in limit on the amount of data that can be sent to the server.

As the name suggests, the .post() method uses the POST method and the .get() method uses the GET Method. The .load() method is a little tricky. It uses the POST method, when we provide the dataToSend as an object -- JavaScript object, that is. Else, it uses the GET method.

Example: .load() Method

Let us see our first example that uses the .load() method to load three simple HTML content from the server. This file has three anchors and for each of these anchors, we attach an event-handler for the click event. Each of these handlers call the .load() method and use it to replace the content of the div element with CSS ID "idDisplayAjax" with the received content from the server.

Please note that each of the event-handler functions call event.preventDefault() for the click event since we would want to prevent the page from being loaded again. This method allows us to cancel the event's response. It would be worth mentioning that the href for these anchors point to the same page, which is "ajax_load.html". We have intentionally kept the href point to the same file since we want to demonstrate that with AJAX, we can do fine even without reloading the page.

 <!doctype html>
 <html>
 <head><h2>List of Nobel laureates</h2></head>

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <!-- This provides lightweight CSS design -->
 <style type="text/css">
 .classDisplay {border: 2px solid black; border-radius: 12px; padding: 5px; width: 18em;}
 </style>

 <a href="./ajax_load.html" id="idPhys">Nobel Prize for Physics   </a><br>
 <a href="./ajax_load.html" id="idChem">Nobel Prize for Chemistry </a><br>
 <a href="./ajax_load.html" id="idLit"> Nobel Prize for Literature</a><br>
 <br>
 <div id="idDisplayAjax" class="classDisplay">The AJAX output will go here!</div>

 <script type="text/javascript">
 $(document).ready(function() {
     $("#idPhys").on("click", function(eventObj) {
         $("#idDisplayAjax").load("phys.html");
         eventObj.preventDefault();
     });

     $("#idChem").on("click", function(eventObj) {
         $("#idDisplayAjax").load("chem.html");
         eventObj.preventDefault();
     });

     $("#idLit").on("click", function(eventObj) {
         $("#idDisplayAjax").load("lit.html");
         eventObj.preventDefault();
     });
 });
 </script>
 </body>
 </html>

We provide below the three files (in the same order): phys.html, chem.html, and lit.html. As noted earlier, these files merely contain pieces of HTML code and are not complete documents by themselves. This is acceptable since the .load() method would simply replace the existing contents of the "#idDisplayAjax" with these new files. And as such, there is no need for these (small) files to have a head, body, etc.

 <!-- Filename: phys.html -->
 <style type="text/css">
     .classPhys {color: blue; font-weight: bold;}
 </style>

 <ul class="classPhys">
     <li> Peter Higgs </li>
     <li> Fran├žois Englert </li>
     <li> Albert Einstein </li>
     <li> Niels Bohr </li>
     <li> Marie Curie</li>
 <ul>
 <!-- Filename: chem.html -->
 <style type="text/css">
     .classChem {color: red; font-weight: bold;}
 </style>

 <ul class="classChem">
     <li> Michael Levitt </li>
     <li> Ernest Rutherford</li>
     <li> Marie Curie</li>
     <li> Linus Pauling</li>
     <li> Wilhelm Ostwald</li>
 <ul>
 <!-- Filename: lit.html -->
 <style type="text/css">
     .classLit {color: green; font-weight: bold;}
 </style>

 <ul class="classLit">
     <li> Alice Munro</li>
     <li> Ernest Hemingway</li>
     <li> Rabindranath Tagore</li>
     <li> Winston Churchill</li>
     <li> Pablo Neruda</li>
 <ul>

With that, let us go ahead and load the file. We load this file by keeping them at the web-server. However, for this example, we can do even without using a web-server. We can simply load the main file by opening it in the browser. Also, as expected, when we load the above file, we do not see content from any of these files.



Figure: Calling the .load() Method

With that, let us go ahead and click these links. As we click each of these links, we would find that the .load() method loads the corresponding HTML file. Here are the three different outputs, each corresponding to different output when clicking these three links.



Figure: Loading the "phys.html" with the .load() Method



Figure: Loading the "chem.html" with the .load() Method



Figure: Loading the "lit.html" with the .load() Method

Examples: .get() and .post() Methods

We could also use the .get() and .post() methods to do the same task as is done by the .load() method in the earlier example. Our next two examples do exactly that.

Our next example uses the $.get() method and is invoked by each of the three event-handlers. Each of the handler passes respective URL ("phys.html", "chem.html", and "lit.html") when invoking the .get() method. In addition, each of these handlers also use a callback function, funcHandleInput(). This callback function is common for all the three handlers. As noted earlier, this is the callback function that gets invoked when we receive input from the server. In terms of functionality, this callback function simply replaces the HTML content of the div element with the one that it receives from the server. This behavior is same as that of the earlier example. The output of these example is same as that of earlier example.

 <!doctype html>
 <html>
 <head><h2>List of Nobel laureates</h2></head>

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <!-- This provides lightweight CSS design -->
 <style type="text/css">
 .classDisplay {border: 2px solid black; border-radius: 12px; padding: 5px; width: 18em;}
 </style>

 <a href="./ajax_get.html" id="idPhys">Nobel Prize for Physics   </a><br>
 <a href="./ajax_get.html" id="idChem">Nobel Prize for Chemistry </a><br>
 <a href="./ajax_get.html" id="idLit"> Nobel Prize for Literature</a><br>
 <br>
 <div id="idDisplayAjax" class="classDisplay">The AJAX output will go here!</div>

 <script type="text/javascript">
 $(document).ready(function() {
     // Common callback function
     function funcHandleInput(dataFromServer) {
         $("#idDisplayAjax").html(dataFromServer);
     }

     $("#idPhys").on("click", function(eventObj) {
         $.get("phys.html", funcHandleInput);
         eventObj.preventDefault();
     });

     $("#idChem").on("click", function(eventObj) {
         $.get("chem.html", funcHandleInput);
         eventObj.preventDefault();
     });

     $("#idLit").on("click", function(eventObj) {
         $.get("lit.html", funcHandleInput);
         eventObj.preventDefault();
     });
 });
 </script>
 </body>
 </html>

The example with the $.post() method is similar to that of the $.get() method. We provide it here for the sake of completeness. The output of this example is same as our earlier examples.

 <!doctype html>
 <html>
 <head><h2>List of Nobel laureates</h2></head>

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <!-- This provides lightweight CSS design -->
 <style type="text/css">
 .classDisplay {border: 2px solid black; border-radius: 12px; padding: 5px; width: 18em;}
 </style>

 <a href="./ajax_post.html" id="idPhys">Nobel Prize for Physics   </a><br>
 <a href="./ajax_post.html" id="idChem">Nobel Prize for Chemistry </a><br>
 <a href="./ajax_post.html" id="idLit"> Nobel Prize for Literature</a><br>
 <br>
 <div id="idDisplayAjax" class="classDisplay">The AJAX output will go here!</div>

 <script type="text/javascript">
 $(document).ready(function() {
     // Common callback function
     function funcHandleInput(dataFromServer) {
         $("#idDisplayAjax").html(dataFromServer);
     }

     $("#idPhys").on("click", function(eventObj) {
         $.post("phys.html", funcHandleInput);
         eventObj.preventDefault();
     });

     $("#idChem").on("click", function(eventObj) {
         $.post("chem.html", funcHandleInput);
         eventObj.preventDefault();
     });

     $("#idLit").on("click", function(eventObj) {
         $.post("lit.html", funcHandleInput);
         eventObj.preventDefault();
     });
 });
 </script>
 </body>
 </html>

Investigation AJAX with Firebug

Let us verify that when we do an AJAX call, it is only the new information that gets transported from the server and not the entire page. To do that, we use Firebug and see requests of type HTML and XHR.

The first figure shows the HTML flow from the Firebug tool. We see that once the page is loaded, the HTML tab shows that the main page ("ajax_load.html") is the only page that is loaded.



Figure: Firebug: HTML panel immediately after loading the page

When we look at the XHR tab, we see that no XHR flows (AJAX request/response) has been made yet.



Figure: Firebug: XHR panel immediately after loading the page

Let us now look at the same two panels after clicking all the three links. We provide these two below. We see that the HTML panel remains the same since none of three anchors lead to getting new HTML pages aka reloading of the HTML page. However, when we look at the XHR panel, we find that there are three XHR requests, one for each of the three HTML content.



Figure: Firebug: HTML panel after clicking all the three anchors



Figure: Firebug: XHR panel after clicking all the three anchors





comments powered by Disqus