Hello everyone,

In today's tutorial, I am going to mention AJAX, show you its tricks, and give examples on its usage with both JavaScript and JQuery.

Ajax (is also a town in Southern Ontario, Canada and a Dutch professional soccer club based in Amsterdam) is, in short, the process of communicating with a server from a webpage, using JavaScript, without leaving the page. Without leaving the page? But how? Can we send our requests without leaving the page? 


Sure, we can do that by using the features of Ajax! We are going to see all these features but before we delve into AJAX, we have some prerequisites to learn.. As it can be seen from the name, JavaScript and XML knowledge is required to be able to grasp the concepts in this tutorial. Please make sure to take a look at these JS tutorials at least to have an idea about these prerequisites.

Alright then let's begin;

First of all AJAX is NOT a programming language. It is a great technique to be able to create dynamic websites. With AJAX, we are able to:

- Update some portions of the website without reloading the page,
- Request data from a server after the page has loaded,
- Receive data from a server after the page has loaded,
- Send data to a server in the background.

Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. XHTML was developed to make HTML more extensible and increase interoperability with other data formats. There are various differences between XHTML and HTML. The Document Object Model (DOM) is a tree structure that represents the page internally in applications, and XHTML and HTML are two different ways of representing that in markup. CSS is a stylesheet language that describes the presentation of an HTML (or XML) document. CSS describes how elements must be rendered on screen, on paper, or in other media.

Who Uses AJAX ?

Examples of websites using AJAX: Google Search, Google Maps, Gmail, YouTube, Facebook, Twitter and many more.

How AJAX Works?


As I said before, we can request data from our server by using AJAX without reloading the page. The object we use to accomplish this operation is called the  XMLHttpRequest object. XMLHttpRequest has been available ever since Internet Explorer 5.5 was released in July 2000. The following figure illustrates the working principle of AJAX.



XMLHttpRequest Methods


abort()--> Cancels the current request.

getAllResponseHeaders()--> Returns the complete set of HTTP headers as a string.

getResponseHeader( headerName ) --> Returns the value of the specified HTTP header.

open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )

Open Method specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications) may be possible.

The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

send( content )--> Sends the request.

setRequestHeader( label, value )--> Adds a label/value pair to the HTTP header to be sent.

Properties of the XMLHttpRequest ObjectDetailed Description
onreadystatechangeStores a function (or the name of a function) to be called automatically each time the readyState property changes
readyStateHolds the status of the object. Changes from 0 to 4: 
0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready
status200: "OK"
404: Page not found

Creating an XMLHttpRequest


Let's have a closer look at the syntax for creating an XMLHttpRequest object:


var xobj;
if (window.XMLHttpRequest) {
    xobj = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xobj = new ActiveXObject("Microsoft.XMLHTTP");
}

Now that we have created our object, we can send requests to the server, read the response and write it to an element on our DOM:

<!DOCTYPE html>
<html>
<body>

<h2>AJAX - Get Method Test - Soysal.TK</h2>

<button type="button" onclick="loadDoc()">Click to request data</button>

<p>Click the button several times to see if the time changes, or if the file is cached.</p>

<p id="responsehere"></p>

<script>
function loadDoc() {
  var xobj;
  if (window.XMLHttpRequest) {
    xobj = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xobj = new ActiveXObject("Microsoft.XMLHTTP");
  }

 // Handles the response when the state of the object changes
  xobj.onreadystatechange=function() {
    if (xobj.readyState == 4 && xobj.status == 200) {
      document.getElementById("responsehere").innerHTML = xobj.responseText;
    }
  };

 // Prevents to get a cached version of the response by using Math.random()
  xobj.open("GET", "demo_get.asp?t=" + Math.random(), true);
  xobj.send();
}
</script>

</body>
</html>

Here is the result;

Let's have a look at another example that uses an XML file to list number of elements:



<!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 2px solid gray;
  border-collapse: collapse;
}
th,td {
  padding: 1px;
}
</style>
<body>

<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="puthere"></table>

<script>
function loadDoc() {
  var xobj;
  if (window.XMLHttpRequest) {
    xobj = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xobj = new ActiveXObject("Microsoft.XMLHTTP");
   }

  xobj.onreadystatechange = function() {
    if (xobj.readyState == 4 && xobj.status == 200) {
      myFunc(xobj);
    }
  };
  xobj.open("GET", "XMLFILE.xml", true);
  xobj.send();
}

function myFunc(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Column1</th><th>Column2</th></tr>";
  var x = xmlDoc.getElementsByTagName("CD");
  for (i = 0; i <x.length; i++) {
    table += "<tr><td>" +
    x[i].getElementsByTagName("COL1")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("COL2")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("puthere").innerHTML = table;
}
</script>

</body>
</html>

In this example we use open method to get the XMLFILE.xml and structure its elements when the state of the object changes by using the myFunc and place them into the element 'puthere'.

Here is the result;


And this is what the XMLFILE.xml looks like;


<CATALOG>
<CD>
<COL2>Empire Burlesque</COL2>
<COL1>Bob Dylan</COL1>
</CD>
<CD>
<COL2>Hide your heart</COL2>
<COL1>Bonnie Tyler</COL1>
</CD>
....
..
.
</CATALOG>

Alright, so far we have covered the XMLHttpRequest object with plain JavaScript and gave two example cases to show its functionality. The next step is to mention the use of AJAX with JQuery which is a fast, small, and feature-rich JavaScript library that allows us to write less code but achieve more. So it is easier to deal with JQuery but some developers don't want to include JQuery in their webpages because of its size. Ultimately the choice is yours as a developer.

JQuery Load Method


The jQuery load() method is a simple, but powerful AJAX method.The load() method loads data from a server and puts the returned data into the selected element. Here is the syntax:


$(selector).load(URL,data,callback);


 This following example is a simple one that replaces a text with another from a file upon an AJAX request.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#puthere").load("demo_test.txt");
    });
});
</script>
</head>
<body>

<div id="puthere"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>


In this example, we waited for the button click and loaded the content from a text file by using the load() method.

Instead of loading the entire content from a file we can just extract an element(#takethis) and place it into (#puthere) in our DOM.

$(document).ready(function(){
    $("button").click(function(){
        $("#puthere").load("demo_test.txt #takethis");
    });
});


HTTP REQUEST: GET vs. POST

Two commonly used methods for a request-response between a client and server are: GET and POST.  GET - Requests data from a specified resource POST - Submits data to be processed to a specified resource GET is basically used for just getting (retrieving) some data from the server.

Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request. Here is the syntax for both of them:

// GET REQUEST SYNTAX
$(document).ready(function(){
    $("button").click(function(){
        $.get("mypage.asp", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

// POST REQUEST SYNTAX

$(document).ready(function(){
    $("button").click(function(){
        $.post("demopost.asp",
        {
          name: "Soysal",
          city: "Ottawa"
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});


//And here is how the ASP file looks like ("demopost.asp"):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>

This is the result for the POST request:


Alright guys, we have come to the end of this tutorial. I hope you found it helpful. Please leave your opinion below and don't forget to share for more! Happy coding!
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..