Saturday, January 7, 2017

Ajax using by plain JavaScript

Why we need Ajax ?

Ajax is needed to make the HTTP request to the server without page refresh, What does this mean? Have you know about when you type something on google which provides suggestions related to your query from google database without loading the page. To See the demo just type some letter on below input box.
Ajax can be used to update any part of the web page without a browser refresh. For example, a website has a block named “Most Visited News”, which shows 5 most visited news items, and it has “More” link at bottom of the block, after clicking this link, there would show all visited news items without a page load. It gives the smooth user experience HTTP request is used for send/receive data to/from a server. A page refresh gives the extra load to the server than a single HTTP request, because after reloading the page, the client sends the total numbers of HTTP requests as many as JavaScript, Images, and CSS files are used on this page.


Normal process for HTTP request

If you want to display new data in your site from database by clicking a link or submitting a form, without using Ajax the architecture would be something like



With the traditional way, for fetching data from a server, the HTTP request from a browser to server happens with page load only. As I said above, the site has a block “Most Visited News”, and a link “More” under this block. It does not use Ajax and after clicking on the link, the new data would display with the page loading.


Ajax process for HTTP request

Below figure shows the client does HTTP request to a server without page load by using Ajax.


With Ajax for performing above more-item task, if you click on “More” link, the browser displays the information without page load and the user even does not know what’s going on the background. A user will have a great user experience with this.

What is Ajax?

Ajax is the sum of Asynchronous JavaScript and XML. To understand this you should have knowledge of JavaScript, HTML and basic about CSS. It sends the data by using XMLHttpRequest object and get the response back from a server.

Let’s understand the code that how do we send/receive data to/from a server. I have created the example module named Ajax.

Initialize the XMLHttpRequest

 
var Ajax = {
 /**
  This Function initiates the XMLHttpRequeset Object,
  the object-path for commmunication between Client and Server.
 **/
 init: function () {
  if (window.XMLHttpRequest) {
   //IE7+, Firefox, Chrome, Opera, Safari
   this.http = new XMLHttpRequest();
  } else {
   // // IE 6 and older
   this.http = new ActiveXObject("Microsoft.XMLHTTP");
  }
             
  this.onReadStateChange();
  
  // It triggers if some error occured with http request
  this.http.onerror = function (err) {
   console.log("Error " + err);
  };
  
  // It triggers if http request is interrupted
  this.http.onabort = function (evt) {
   console.log("Error abort " + evt);
  }
 },


In above function init,  you are just initiating the XMLHttpRequest object through new XMLHttpRequest() for latest browser and new ActiveXObject("Microsoft.XMLHTTP"); is for IE6 and older. The client uses this object to send the HTTP request to server.

Send data/request to server

/**
 This function is used to send the http
 request to server, The paramter "path" expects for server path
 and "data" for sending to server.
**/
send: function (method, data, path, cb) {
 console.log('send');
 /** callback function is initiate and
  will be invoked after got response from server **/
 this.cb = cb; 
 if(method == 'GET'){
  // To send data in GET method, we prepend '?' to the data
  path =  path+'?'+data; 
  data = null;
  this.http.open(method,  path, true);
 } else {
  this.http.open(method,  path, true);
  
  /** It sends the data by using POST method as key pair value like,
  with name=suman&age=30, server gets value as name = suman; and age = 30; **/
  this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 }
 // Sending request to server
 this.http.send(data); 
}


The function send is used to initialize HTTP request and send it to server. It accepts the path of a server, a method either it’s GET or POST, and the data as key pair value, like name=suman.

It has also expected callback function which will be invoked after fetching the data from a server.
To initialize HTTP request and for sending request to server, this.http.open(method,  path, true) and  this.http.send(data) are used.

Get response from server 

/**
 This Function triggers to show the HTTP request status, 
 it gets the data from server if request is succeed
**/
onReadStateChange: function () {
 console.log('init');
 var that = this;
 this.http.onreadystatechange = function (evt) {
  console.log('ready state ' + that.http.readyState + ' status code ' + that.http.status);
  // It means the fetch operation has been completed
  if (that.http.readyState == 4) {
   if (typeof that.cb != 'undefined') {
    // 200, means http request is successful.
    // with readyState 4 means, data is downloaded successfully
    if (that.http.status == 200) {
     that.cb({'data' : that.http.responseText});
    } else {
     that.cb({'error' : evt});                            
    }
   }
  }
 }
},
};


This method onReadStateChange  receives the data from server, gets the error if something wrong happens in client or a server, and shows the status of HTTP request. 

In this method, readyState 4 and HTTP status 200 show that the data is downloaded successfully and there would trigger the callback function which was received during sending the HTTP request in send method.

Use the Ajax module,

var data = 'rdata=hello&name=suman'; 

// The path of server to which the HTTTP request is sent.
var path = 'server.php'; 

/** The callback function will trigger, 
 after fetching the data from server **/
function afterResponse(response){ 
 var result = response.hasOwnProperty('error') ? "Something bad happens." : response.data;
 document.querySelector("#result h3").innerHTML = result;
}

Ajax.init();
Ajax.send('POST', data, path, afterResponse);


By above code, we initializing the module with providing method, data, path, and callback function afterResponse. Inside this callback function you can perform the action based on a response given by server.

About readyStage and HTTP Status code

There is two type of information we should know about like, readyState shows the state of HTTP request client and HTTP status shows that request has been completed successfully or not.
You can get more about readyState and status code.

Below table shows different information about request status by the different combination.

readyState
HTTP status
description
1
0
The request has been opened but not sent yet.
2
200
The request to sever has been sent and it’s successful.
3
200
The data is being downloaded from server.
4
200
The data is downloaded on client successfully from server.

You can get the source code by Ajax using plain JavaScript.