Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views8 pages

Ajax

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

PSIT-Pranveer Singh Institute of Technology

Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

UNIT 3: AJAX - ASYNCHRONOUS JAVASCRIPT AND XML

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.

3. HOW AJAX WORKS?

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.

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

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.

3. AJAX LIFE CYCLE


Normally, sending an AJAX request to the server and getting back the response (life cycle events)
from the server involve the following steps:

• 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.

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

AJAX Lifecycle

4. AJAX XMLHttpRequest Object

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.

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

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.

4.1. CREATE XMLHttpRequest OBJECT

A new object of XMLHttpRequest is created like this:

//Creating a new XMLHttpRequest object


var xmlhttp;

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.

4.2. XMLHttpRequest METHODS

To send requests and set request attributes, XMLHttpRequest object provides following methods:

4.2.1. open(method, url, isAsync, userName, password)

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

method required Specifies the HTTP method.


Valid value GET, POST, HEAD, PUT, DELETE, OPTIONS

URL required Specifies URL that may be either relative parameter or


absolute full URL.

asynchronous_flag optional Specifies whether the request should be handled


asynchronously or not.
Valid value: true, false
Default value: true
true means without waiting for a response, next code

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

processing to execution queue on after the send() method.


false means wait for a response after the next code
processing.

username optional Specifies username of authorize user otherwise set to null.

password optional Specifies password of authorize user otherwise set to null.

xmlhttp.open("GET","report_data.xml",true);
xmlhttp.open("GET","sensitive_data.xml",false);
xmlhttp.open("POST","saveData",true,"myUserName","somePassord");

The open() method:


• throws a “SyntaxError” if either method is not a valid HTTP method or url cannot be
parsed.
• throws a “SecurityError” if method is a case-insensitive match for ‘CONNECT’,
‘TRACE’, or ‘TRACK’.

4.2.2. setRequestHeader(name, value)

Upon successful initialization of a request, the setRequestHeader() method of the


XMLHttpRequest object can be invoked to set HTTP headers in the request.

xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("User-Agent", "navigator.userAgent");

The setRequestHeader() method:


• throws a “InvalidStateError” if either state is not opened or the send() flag is set.
• throws a “SyntaxError” if name is not a header name or if value is not a header value.

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.

xmlhttp.send(null); //HTTP GET

xmlhttp.send( '{"id":"23423"}' ); //HTTP POST

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.

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

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.

//Abort the processing


xmlhttp.abort();

5. ASYNCHRONOUS AND SYNCHRONOUS AJAX REQUESTS

XMLHttpRequest object is capable of sending synchronous and asynchronous requests, as required


from the webpage. This behaviour is controlled by the third parameter of open() method.
This parameter is set to:

• true – asynchronous requests


• false – synchronous requests

//Asynchronous request as third parameter is true


xmlhttp.open("GET", "report_data.xml", true);
//Synchronous request as third parameter is false
xmlhttp.open("GET", "report_data.xml", false);
The default value is true if it is not provided.
Asynchronous AJAX Requests do not block the webpage, and the user can continue to interact with
the other elements on the page while the server is processing the 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.

5.1. SYNCHRONOUS AJAX REQUEST EXAMPLE

Given below is a JavaScript program to show how to make synchronous requests with AJAX.

var request = new XMLHttpRequest();


request.open('GET', '/bar/foo.txt', false); //"false" makes the request synchronous
request.send(null);
if(request.status === 200){
//request successful; handle the response
}else{

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

//Request failed; Show error message


}

5.2. ASYNCHRONOUS AJAX REQUEST EXAMPLE

Given below is a JavaScript program to show how to make asynchronous requests with AJAX.

var request = new XMLHttpRequest();


request.open('GET', '/bar/foo.txt', true); //"true" makes the request asynchronous

request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200){
//request succeed
}else{
//request failed
}
}
};

request.send(null)

5.3. onreadystatechange Event

In the above example, onreadystatechange is an event listener registered


with XMLHttpRequest request. onreadystatechange stores a function that will process the response
returned from the server.

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.

5.4. HANDLING RESPONSE FROM 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

Department of Computer Science & Engineering


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

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:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200){


document.getElementById("message").innerHTML = xmlhttp.responseText;
}
else {
alert('Something is wrong !!');
}
}

Department of Computer Science & Engineering

You might also like