Ajax
Ajax
Ajax
1. INTRODUCTION
a) AJAX is a Client-side web technique. With AJAX, we can able to make background server
calls for fetching addition data, updating some portion in web page without refreshing the
whole page.
b) In other words, AJAX allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. If an application is not using AJAX, it will
have to load a new webpage on every request user made.
c) AJAX is based on JavaScript and HTTP requests.
d) AJAX is not a new programming language, but a new way to use existing standards with DOM
manipulating.
e) JavaScript is help to an AJAX to make background AJAX calls for fetching certain amount of
data.
f) Without AJAX, traditional web page takes a longer time to finishing round trip process for
getting a data form the server. So, it's time-consuming process even if small changes are in web
page, entire web page reload.
g) In a traditional webpage, you can't update small portion without reloading page. So here Ajax
is help us to background server calls for fetching data and update new contain without reloading
page.
h) AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
2. BENEFITS OF AJAX
a) Using AJAX, you can create better, faster, and more user-friendly web applications.
b) AJAX is based on JavaScript, CSS, HTML and XML etc. So, you can easily learn.
c) AJAX behaviour and works is like a desktop application. So, Ajax use for creating a rich web
application.
Let's take one example we have a website for user management system.
Without AJAX, whenever we want to access account, we press login link. New login page open
and enter username, password, and login successfully. It's time-consuming process, inefficient for
only small amount data (Login page) exchange required.
With AJAX, we want to access account, we press login link. Background JavaScript call to a
server for fetching login portion and update/add to current web page. Now, we can enter username,
password and login successfully. It takes small bit of time for this process.
It is essential to understand that AJAX is not a single technology but a group of technologies, e.g.
HTML, CSS, DOM, and JavaScript, etc. HTML and CSS can be used in combination to mark up
and style information of the webpage.
HTML/CSS is website markup language for defining web page layout, such as fonts style and
colours.
JavaScript special object XMLHttpRequest that was designed by Microsoft. XMLHttpRequest
provides an easy way to retrieve data from web server without having to do full page refresh. Web
page can update just part of the page without interrupting what the users are doing.
Document Object Model (DOM) method provides a tree structure as a logical view of web page.
XML for retrieving any type of data, not just XML data from the web server. However, you can
use other formats such as Plain text, HTML or JSON (JavaScript Object Notation). and it supports
protocols HTTP and FTP.
The DOM is accessed with JavaScript to dynamically display the information, and allow the user
to interact with, the information presented. JavaScript and the XMLHttpRequest object provide
a method for exchanging data asynchronously between the browser and the server to avoid full
page reloads.
Note: In recent years, the essence of XML has been reduced. JSON (JavaScript Object Notation)
is often used as an alternative format for data interchange, although other formats such as
preformatted HTML or plain text can also be used for data purpose.
• User type the URL of a webpage in the browser’s address bar and hit ENTER. The page
is loaded in browser.
• Some user action triggers an event, like the user clicking a button.
• Event fires the AJAX call, and sends a request to a server.
• The server takes the input from AJAX request, and processes the request. The server
also prepares the response if required.
• The server sends the data back to the webpage that made the request.
• Another JavaScript function, called a callback function, receives the data in the server
response, and updates the web page.
AJAX Lifecycle
The core of AJAX is the XMLHttpRequest object (available in client-side scripting languages like
JavaScript). The XMLHttpRequest object is used to exchange the data with a live server behind the
scenes. All modern browsers (IE, Firefox, Chrome, Safari, and Opera) have a built-in
XMLHttpRequest object.
If you are using IE 5 or IE6 (I wonder if someone still uses it), then ActiveXObject will be used for
server communication to send ajax requests.
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
This xmlhttp variable can be re-used to send multiple ajax requests, without creating a new object for
each request.
To send requests and set request attributes, XMLHttpRequest object provides following methods:
The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through
the open() method. The open() specifies the type of request (GET, POST etc.), the request URL, and if
the request should be handled asynchronously or not.
The 4th and 5th parameters are the username and password, respectively. These parameters can be
provided for authentication and authorization purposes if the server needs it.
Syntax
open("method","URL"[,asynchronous_flag[,"username"[,"password"] ] ] )
PARAMETER REQUIRED DESCRIPTION
xmlhttp.open("GET","report_data.xml",true);
xmlhttp.open("GET","sensitive_data.xml",false);
xmlhttp.open("POST","saveData",true,"myUserName","somePassord");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("User-Agent", "navigator.userAgent");
4.2.3. send(payload)
To finally send an HTTP request, the send() method of the XMLHttpRequest must be invoked. This
method accepts a single parameter containing the request body to be sent with the request.
The payload is necessary in POST requests. For GET and HEAD methods, simply pass null as a
parameter.
The send() method throws an “InvalidStateError” if either state is not opened or the send() is already
invoked and response has not been received yet.
4.2.4. abort()
It aborts the request if the readyState of the XMLHttpRequest object has not yet become 4 (request
complete). The abort() method ensures that the callback method does not get invoked in an
asynchronous request.
We should always use asynchronous AJAX requests because a synchronous AJAX Request makes the
UI (browser) unresponsive. It means the user will not be able to interact with the webpage until the
request is complete.
Synchronous requests should be used in rare cases with utmost care. For example, synchronous AJAX
requests should be used if we’re embedding a new JavaScript file on the client UI using AJAX and
then referencing types and objects from that JavaScript file. Then the fetching of this new JS file
should be included through using a synchronous AJAX Request.
Given below is a JavaScript program to show how to make synchronous requests with AJAX.
Given below is a JavaScript program to show how to make asynchronous requests with AJAX.
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200){
//request succeed
}else{
//request failed
}
}
};
request.send(null)
The function will be called for all important events in request’s life cycle. Every time a step is
completed in request processing, the value of readyState property will be changed and set to one of
the given integer values:
• 0 : request is not initialized, i.e., After the XMLHttpRequest object is created but the
open() is yet to be called.
• 1 : server connection established, i.e., After open() method called but send() method is
yet to be called.
• 2 : request received, i.e., After send() method is called.
• 3 : processing request, i.e., After the browser has established a communication with the
server, but before the server has completed the response
• 4 : request finished and response is ready to be handled, i.e., After the request has been
completed, and the response data has been completely received from the server.
To fetch the response sent from the server, responseText or responseXML property of
the XMLHttpRequest object is used. If the response from the server is XML, and you want to parse it
as an XML object, use the responseXML property. If the response from the server is not XML, use
the responseText property.
• responseText : Get the response from server as a string
• responseXML : Get the response from server as XML
Given below is a JavaScript program that fetches the response sent from the server for an AJAX
request: