Friday, June 21, 2024

Introduction to AJAX

Introduction to AJAX (Asynchronous JavaScript and XML)

Normally a web browser requests a web page from web server and the web server responds by returning the requested web page. As soon as the web page loads in to the browser, the connection between the web browser and the web server is terminated.

This is the traditional web model used in the communication between the web server and browser. If a request is made for the same or another page, the same process is repeated again.

Whenever a request is sent by the user for a page, the existing page has to be reloaded to display the new information. New information or a new page is displayed only after the page is reloaded. Sometimes this process is very annoying for the user experience because entire page is rendered again.

If you are creating a large web application like YouTube, then obviously there will be a lot of web elements in it. In such a situation, if the page is reloaded repeatedly while interacting with every small element, then your web application will create very bad user experience.

For example, suppose that you are watching a video on YouTube. You like this video and you click on the Like button to like it. If the entire page reloads as soon as you click on the Like button, you will not like it at all. Maybe you would never click the Like button. But this does not happen. Whenever you click the Like button for a video while watching the YouTube video, the page does not reload; only the Like button is updated and the number of likes is increased. The video continues to play without any problem. How does this happen? YouTube uses AJAX for this. 

So the question is : what is AJAX?

The full form of AJAX is Asynchronous JavaScript and XML. You can call it a set of techniques or methodology which is used to create asynchronous web pages using several web technologies (HTML & CSS, JavaScript, DOM, XML). 

Now the question is: What are asynchronous web pages?

Asynchronous web pages are such web pages in which the entire page does not need to be loaded for some elements to be updated. New content is dynamically loaded into the web page. In such pages, processing is done in the background. The user does not feel any interference while happening this process. So the question is: how does this happen? You will know about this in the AJAX Working section. Before that, let us try to know about the core components, advantages and disadvantages of AJAX.

Core Components of AJAX

As I told you earlier, in AJAX, many technologies are combined together to generate asynchronous web pages. These technologies are the core components of AJAX. They are given below.

  • HTML & CSS - HTML and CSS are used for presentation. By using HTML and CSS, you can design a beautiful web page.
  • JavaScript - It is used to generate client side events which are handled and processed by JavaScript.
  • DOM (Document Object Model) - DOM is used to access data from inside the page and to present data dynamically.
  • XMLHttpRequest Object - This object is used to send and receive data asynchronously to the server.

Advantages of AJAX

Below are given some advantages of AJAX.

  • With the help of AJAX, you can create fast, dynamic websites.
  • Because JavaScript is a client side scripting language, so all the processing does not happen on the server only. Some process also happens on the client machine. This reduces the load on the server and makes processing fast.
  • Better user experience is possible through AJAX because AJAX does processing in the background. This does not interfere with the user activities. The page does not hang to receive data from server.
  • With AJAX, you have open source JavaScript libraries available which you can use to improve your web application.

Disadvantages of AJAX

Some disadvantages of AJAX are given below.

  • If JavaScript is disabled in the user's web browser, AJAX based web application will not work.
  • Because the data of the web page is loaded dynamically, it is not a part of the web page. This is the reason why search engines cannot see such data and do not index it.
  • When you use AJAX, the Back and Refresh buttons do not function properly.
  • Due to asynchronous mode, if the server takes time to process, then the page looks annoying.

Working of AJAX

The working of AJAX is explained by a diagram below.

As you can see in the diagram above, the first request by the web browser and the first response by the web server are processed like a traditional web model. After this, the subsequent requests, whenever data has to be fetched back from the server, this task is done by sending a request locally through JavaScript.

For example, if the server has to update when the user clicks on the like button, then for this the onclick event of JavaScript has to be handled. When this event is generated, event handler function is called. In this function, you will pass this request to the server using the XMLHttpRequest Object.

This request reaches the server through the AJAX engine. You will be told about this object in a separate tutorial.

The AJAX engine is on the client side only. The AJAX engine is nothing but a combination of JavaScript and XMLHttpRequest object. The AJAX engine will establish a connection to the server in background and update the page e.g. the number of likes on the page.

The AJAX engine performs this task without disturbing the web page. The server will send the updated data back to the AJAX engine. Any format from HTML to XML and JSON can be processed by AJAX engine. JavaScript updates the same element with the data sent by AJAX engine.

Where are AJAX used

AJAX has been used by many big web applications. For example, when you search a term on Google, the suggestions shown to you are shown by AJAX only. As soon as you type a term, AJAX works in the background and fetches suggestions for you from the server.

Another example of AJAX is YouTube or Facebook like button. When you like a post or video, the number of likes increases without reloading the page. This is also done by AJAX.

Introduction to XMLHttpRequest Object

XMLHttpRequest is an API in the form of a simple object. Its methods transfer data between the browser and the server. This object is provided by JavaScript. The main purpose of this object is to modify the loaded page repeatedly.

The XMLHttpRequest object is the most important component of AJAX. AJAX cannot work without XMLHttpRequest object. The main feature of AJAX, updating elements without reloading the page, is implemented by XMLHttpRequest object.

All modern browsers support XMLHttpRequest object. Internet Explorer 5 and 6 use ActiveXObject. This object is also used for older versions of Internet Explorer. All other browsers have built-in support for XMLHttpRequest object.

Data can be processed in the form of XML, JSON (JavaScript Object Notation) and plain text by the XMLHttpRequest object. Therefore, AJAX is very reliable and widely used. This object also works with other protocols besides the HTTP protocol.

XMLHttpRequest Object Properties

The properties available with the XMLHttpRequest object are described below.

readyState

This property stores the current status of the XMLHttpRequest object. Status is defined by numbers from 0 to 4. Each number has a meaning. This status keeps changing during processing.

  • 0 - This status number indicates that the request has not been initialized yet.
  • 1 - This status indicates that the server connection has been established.
  • 2 - This status indicates that the request has been received.
  • 3 - This status indicates that the request is being processed.
  • 4 - This status indicates that the processing of the request has been completed and the response is ready to be sent.

onreadystatechange

This property of XMLHttpRequest object stores the name of the function which will be called every time the readyState changes.

responseText

This property returns the response data as a string. You can store its value in any normal JavaScript variable and display it.

responseXML

This property returns the response data as XML data.

status

This property returns the status. If the request is not successful, it will return 404 (NOT FOUND) status. If the request is successful, it will return 200 (OK).

statusText

This property returns the status as text. If the request is successful, OK will be returned, otherwise NOT FOUND will be returned as text.

XMLHttpRequest Methods

The methods available with XMLHttpRequest Object are given below.

open(method,URL,Async,UserName,Password)

This method is the most important method of XMLHttpRequest Object. Connection to server is established through this method. 5 parameters can be passed in this method. These are explained below.

  1. Method - With this parameter you define the method used to establish the connection. In this parameter you pass one value from GET or POST.
  2. URL - With this parameter the location of the file stored on the server is defined.
  3. Async - The value of this paramter is given in true and false. With this parameter you define whether the data is to be accessed synchronously or asynchronously.
  4. UserName - With this parameter you define the user name to establish the connection.
  5. password - With this parameter you define the password to establish the connection.

send(String)

This method is used to send the request to the server. This method is used in case of POST requests.

send()

This method is used to send a request to the server. This method is used in case of GET requests.

new XMLHttpRequest()

This method creates a new XMLHttpRequest object.

setRequestHeader()

This method adds a pair of label/value to the header to be sent.

getResponseHeader()

This method returns some specific header information.

getAllResponseHeaders()

This method returns complete header information.

abort()

This method cancels the current request.

Creating XMLHttpRequest Object

To create an XMLHttpRequest object, you use the new XMLHttpRequest() method. Its general syntax is given below.

var xhr = new XMLHttpRequest();

In the above syntax, xhr is a JavaScript variable that will store the XMLHttpRequest object. Creating an XMLHttpObject is explained with an example below.

var xmlHttp = new XMLHttpRequest();

If the browser is Internet Explorer 5 or 6, then you will create an XMLHttpObject as follows.

var = new ActiveXObject("Microsoft.XMLHTTP");

Introduction to AJAX Request

Just like the traditional web model, in AJAX also request is sent to the server and response is received. The only difference is that this process is performed by AJAX in the background without disturbing other page elements.

Request plays an important role in the working of AJAX. According to the request, it is decided whether the page elements will be loaded synchronously or asynchronously. Mostly the request is sent when an event is generated. For this, JavaScript and XMLHttpObject are used.

For example, the user has clicked on a link. Now the necessary information related to this link has to be obtained asynchronously from the server. In this situation, AJAX request will be sent.

The process of sending request to the server by AJAX is being described in the steps below.

First of all, the event generated from the user is handled by JavaScript.

For this, JavaScript calls a function.

In the function, XMLHttpRequest object is created by JavaScript.

Finally, to send the request to the server, the open() and send() methods of XMLHttpObject are called in the function.

Methods Used For AJAX Request

The methods of XMLHttpObject used to send data to the server are described below.

open()

This method is used to establish a connection with the server. This method is called on XMLHttpObject. 3 arguments are passed in this method. Its general syntax is given below.

xmlHttp.open(method, url, async);

  1. method - The first argument of the open() method is the method that you use to send data to the server. This method also tells the type of your request. For its argument, you define a value from GET or POST. You will be told about GET and POST later.
  2. url - The second argument is the url of the file that you want to load as a response.
  3. async - Through the third argument of open() method, you define whether you want to load the response synchronously or asynchronously. Hence, you define the value of this argument as true or false.

send()

This method is used to send the request. You call it on XMLHttpObject. The general syntax of this method is given below.

If you are establishing a connection to the server through GET method request, then you will use the syntax given below for this.

xmlHttp.send(); //For GET Request method

If you are establishing a connection to the server through POST method request, then you will use the syntax given below for this.

xmlHttp.send(string);

When you use POST request method, string is passed as argument in send method. This string is written in double quotes. It is written in the pair of name=value. This string is the value which is required to send data to the server. Such as username, password etc. Its example is given below.

xmlHttp.send("userName=dummy");

Types of AJAX Request

AJAX requests can be divided into 2 categories.

  1. Synchronous - When browser waits for the completion of the AJAX request before executing any other code, then you will send this type of request. For this type of request, the async parameter of the open() method is defined as false. This type of request is not recommended.
  2. Asynchronous - In this type of request, processing is done in the background, which is a feature of AJAX. For this type of request, the value of the async parameter of the open() method is defined as true. By default, AJAX requests are sent in asynchronous mode only.

These two types of AJAX requests are being explained below with examples.

Example

For asynchronous requests, you have to define a function. In this function, it is checked whether the response is ready by the server. Also, it is checked whether the status is ok or not. After this, the response of the server is displayed using DOM.

It is used to load the response asynchronously into the DOM. For this you use the responseText property of the XMLHttpRequest object. Its example is given below.


<html>
  <body>
    <button type="button" onclick="myFunction()">Click here</button>
    <p id="response"></p>
    <script type="text/javascript">
      function myFunction() {
        var xmlHttp = new XMLHttpRequest(); //Creating XMLHttpObject request

        xmlHttp.open("GET", "info-file.txt", true); //Open Method
        xmlHttp.send(); //Send method

        xmlHttp.onreadystatechange =
          function () //For detecting response ready state
          {
            if (this.readyState == 4 && this.status == 200) {
              //Checking ready state & request status
              document.getElementById("response").innerHTML = this.responseText; //Displaying response
            }
          };
      }
    </script>
  </body>
</html>

If the request is not asynchronous then you do not need to define a function. For this, you can display the response directly from the responseText property after the send method. Its example is given below.


<html>
  <body>
    <button type="button" onclick="myFunction()">Click Here</button>

    <p id="result"></p>

    <script type="text/javascript">
      function myFunction() {
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "info-file.txt", false);
        xmlHttp.send();
        document.getElementById("result").innerHTML = xmlHttp.responseText;
      }
    </script>
  </body>
</html>

Introduction to AJAX Server Response

In AJAX, the process of response from the server is different from the traditional web model. In the traditional model, the response is loaded directly in the web browser, whereas to get the AJAX response, you use properties like responseText and responseXML.

The AJAX response model provides several important advantages over the traditional web model.

Through AJAX, the response can be obtained without loading the entire web page.

Through AJAX, the response can also be obtained in JSON format.

Steps of AJAX Response

The process of AJAX response is being explained in the steps below.

If the request is asynchronous, then first of all a function is defined in the onreadystatechange property which will be called when the readyState changes.

Because the function defined in the onreadystatechange property will be called every time the status changes. Therefore, at the beginning of this function, it will be checked whether the readyState is 4? And whether the status is OK?

If the condition is true, the response is displayed using the responseText and responseXML properties along with the DOM. This object is used for this.

If the request is synchronous, then there is no need to create a function and check the condition.

In the case of a synchronous request, the response is displayed using the XMLHttpRequest object.

AJAX Server Response Properties

The properties used for AJAX server response are explained below.

responseText Property

This property is used to get the server's response as a string. If the request is asynchronous, then you will use it inside the function with the DOM in this way.

<html>
  <body>
    <p id="Response"></p>

    <script type="text/javascript">
      //Creating & sending request

      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open("GET", "info.txt", true);
      xmlHttp.send();

      //End of request

      //Getting response

      xmlHttp.onreadystatechange = function () {
        if (readyState == 4 && status == 200) {
          //Checking for status
          document.getElementById("Response").innerHTML = this.responseText;
        }
      };

      //End of response
    </script>
  </body>
</html>


If the request is synchronous then you can use it directly like this:
<html>
  <body>
    <p id="Response"></p>

    <script type="text/javascript">
      //Creating & sending request
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open("GET", "info.txt", false);
      xmlHttp.send();
      //End of request

      //Getting response

      document.getElementById("Response").innerHTML =
        X - H - RObject.responseText;

      //End of response
    </script>
  </body>
</html>

responseXML Property

You use this property to get response from the server in the form of XML. The most important thing you should know about using this property is that this property returns an XML DOM object.

You display the information through this object only. The rest of the process is just like the responseText property. Its example is given below.


<html>
  <body>
    <p id="Response"></p>

    <script type="text/javascript">
      //Creating & sending request

      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open("GET", "info.txt", true);
      xmlHttp.send();

      //End of request

      //Getting response

      xmlHttp.onreadystatechange = function () {
        if (readyState == 4 && status == 200) {
          var xmlDoc = xmlHttp.xmlResponse; //Getting XML object
          var res = xmlDoc.getElementByTagName("Name");
          var response = (document.getElementById("Response").innerHTML = res);
        }
      };

      //End of response
    </script>
  </body>
</html>


AJAX Server Response Methods

The methods used in AJAX server response are given below.

getResponseHeader() Method

This method returns specific header information from the server response. For example, you want to know when the last file that you are accessing from the server was modified.

In case of asynchronous requests, it is called with this object and in case of synchronous requests, it is called with XMLHttpRequest object.

No comments:

Post a Comment

Hot Topics