You are on page 1of 39

INTRODUCTION TO

AJAX

Overview of Ajax.
The basics of Ajax.
Example programs using GET and POST
method.
03/20/23 Dept of CSE, NMAMIT, Nitte 1
What is AJAX
 AJAX = Asynchronous JavaScript And XML.
 AJAX is not a programming language.

 AJAX is a technique for creating fast and dynamic


web pages.
 AJAX allows web pages to be updated asynchronously
by exchanging small amounts of data with the server
behind the scenes.
 This means that it is possible to update parts of a web
page, without reloading the whole page.

03/20/23 Dept of CSE, NMAMIT, Nitte 2


The Real Ajax
 In the traditional web application model the browser itself is responsible
for initiating request to, and processing requests from, the web server.

 The Ajax model provides an intermediate layer called an Ajax Engine


to handle this communication.

 An Ajax Engine is really just a JavaScript object or function that is


called whenever information needs to be requested from the server.

 Instead of the traditional model of providing a link to another resource


(such as another web page), each link makes a call to the Ajax Engine,
which schedules and executes the request.

03/20/23 Dept of CSE, NMAMIT, Nitte 3


 The request is done asynchronously, meaning that code execution
doesn’t wait for a response before continuing.
 The server-which traditionally would serve up HTML, images, CSS
or JavaScript is configured to return data that the Ajax engine can
use.
 This data can be plain text, XML or any other data format
 The requirement is that, the Ajax should understand and interpret
the data.
 When Ajax engine receives the server response, it goes into action,
often parsing that data and making several changes to the user
interface based on the information it was provided
 Because this process involves transferring less information than the
traditional web application model, user interface updates are faster
and user is able to do his work more quickly

03/20/23 Dept of CSE, NMAMIT, Nitte 4


Traditional Web Application Model

HTML, Images,
CSS, JavaScript
Data
Web Browser
DataBase
HTTP Request
Query/Data
Request
Web Server

03/20/23 Dept of CSE, NMAMIT, Nitte 5


Ajax Web Application Model
AJAX is a new web application model which defines new user
experience to the end user. It enhances web experience for users.

Web Browser
HTML,
CSS Data Data
User Ajax
Interface Engine DataBase
JavaScript Call HTTP
Request Query/Data
Request
Web Server

03/20/23 Dept of CSE, NMAMIT, Nitte 6


What is AJAX?
AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:


A browser built-in XMLHttpRequest object (to request data from a

web server)
JavaScript and HTML DOM (to display or use the data)

03/20/23 Dept of CSE, NMAMIT, Nitte 7


Implementing AJAX…

1. Using Hidden Frame (GET and POST method)

2. Using Hidden IFrame (GET and POST method)

3. Using XMLHttp (GET and POST method)

03/20/23 Dept of CSE, NMAMIT, Nitte 8


Using XMLHttp
AJAX works by employing an XMLHttpRequest object to
pass requests and responses asynchronously between client
and server.

03/20/23 Dept of CSE, NMAMIT, Nitte 9


Creating an XMLHttp Object

For IE,

var oXmlHttp = new ActiveXObject( “Microsoft.XMLHttp”);

For Modern Browsers,


variable = new XMLHttpRequest();

Example
var xhttp = new XMLHttpRequest();

03/20/23 Dept of CSE, NMAMIT, Nitte 10


XMLHttpRequest Object Methods

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server. Used for GET requests
send(string) Sends the request to the server. Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

03/20/23 Dept of CSE, NMAMIT, Nitte 11


XMLHttpRequest Object
Properties

Property Description
onreadystatechange Defines a function to be called when the
readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

03/20/23 Dept of CSE, NMAMIT, Nitte 12


Property Description
responseText Returns the response data as a
string
responseXML Returns the response data as XML
data
status Returns the status-number of a
request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the 
Http Messages Reference
statusText Returns the status-text (e.g. "OK"
or "Not Found")

03/20/23 Dept of CSE, NMAMIT, Nitte 13


Working of AJAX

1. Create an instance of XMLHttpRequest object to send an Http


request from client to the server:
xmlhttp = new XMLHttpRequest();

2. Create a request to server by using open (method, url, async) method


of XMLHttpRequest object.
xmlhttp.open (“GET”, “file.jsp”, true);
xmlhttp.send();

03/20/23 Dept of CSE, NMAMIT, Nitte 14


 open method has three parameters:
1. First parameter is the method POST/GET depends on our request,
POST is secure than GET.

2. Second parameter is the destination, where we need to send the


request. It may be file path, url or url patterns.

3. Third parameter having values true/false, true means asynchronous


data transfer, false means synchronous.

03/20/23 Dept of CSE, NMAMIT, Nitte 15


 Sending a request to the server by using the send() method.
 send(string) method sends the request to the server.

POST request format:


xmlhttp.open(“POST”, “file.jsp”);
xmlhttp.setRequestHeader(“Content-type”,”application/x-www-
form-urlencoded”);
xmlhttp.send(“fname=EME & lname=“Technologies”);

GET request format:


xmlhttp.open(“GET”, “file.jsp? fname=EME &
lname=“Technologies”);
xmlhttp.send();

03/20/23 Dept of CSE, NMAMIT, Nitte 16


XMLHttpRequest properties
 It contains 6 properties that represent the request in various formats
such as XML, plaintext.
1. onreadystatechange: A function will be stored and will be called
automatically each time the ready state property changes.
2. readystate:
0 – request not initialized
1 – connection being established with the server
2 – request received from client
3 – request being processed
4 – request finished and response is ready.

03/20/23 Dept of CSE, NMAMIT, Nitte 17


3. responseText - String version of data returned from server process

4. responseXML - DOM-compatible document object of data returned


from server process

5. Status
200 – OK
404 – Page not found
So when readystate=4 and status =200 then everything will be perfect
means we get the response from the server and out webpage will be
modified with response text/XML.

6. Statustext - String message accompanying the status code

03/20/23 Dept of CSE, NMAMIT, Nitte 18


 Status Code:
 200 (OK) – resource was found and all was well

 304 (NOT MODIFIED) – Resource has not modified since last

request
 401 (UNAUTHORIZED) – client is not authorized to access the

resource
 403 (FORBIDDEN) – client failed to gain authorization

 404 (NOT FOUND) – resource doesn’t exist at the given location

03/20/23 Dept of CSE, NMAMIT, Nitte 19


AJAX - The XMLHttpRequest Object
The onreadystatechange Property

After a request to the server, we need a function that can receive the
data that is returned by the server.
The onreadystatechange property stores the function that will process

the response from a server.


 The following code defines an empty function and sets the

onreadystatechange property at the same time:

xmlHttp.onreadystatechange=function() { // some code here }

03/20/23 Dept of CSE, NMAMIT, Nitte 20


The readyState Property
The readyState property holds the status of the server's response.

Each time the readyState changes, the onreadystatechange function

will be executed.
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{ // some code here }
}

03/20/23 Dept of CSE, NMAMIT, Nitte 21


Send a Request To a Server:
To send a request to a server, we use the open() and send() methods of
the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
1.open() method will open specific url ( for open on server)

2.send() method Sends an HTTP request to the server and receives a


response.
Method Description
open(method, url, Specifies the type of request
async)
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
03/20/23 Dept of CSE, NMAMIT, Nitte 22
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:


A cached file is not an option (update a file or database on the server).

Sending a large amount of data to the server (POST has no size

limitations).
Sending user input (which can contain unknown characters), POST is

more robust and secure than GET.

03/20/23 Dept of CSE, NMAMIT, Nitte 23


GET Requests
A simple GET request:

Example:
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

If you want to send information with the GET method, add the
information to the URL:

Example:
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();

03/20/23 Dept of CSE, NMAMIT, Nitte 24


POST Requests
A simple POST request:
Example:
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

To POST data like an HTML form, add an HTTP header with


setRequestHeader(). Specify the data you want to send in the send() method:
Example:
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send("fname=Henry&lname=Ford");

setRequestHeader(header, Adds HTTP headers to the request


value) header: specifies the header name
03/20/23 Dept of CSE, NMAMIT, Nitte 25
value: specifies the header value
The url - A File On a Server:
The url parameter of the open() method, is an address to a file on a
server:

xhttp.open("GET", "ajax_test.asp", true);

The file can be any kind of file, like .txt and .xml, or server scripting
files like .asp and .php (which can perform actions on the server before
sending the response back).

03/20/23 Dept of CSE, NMAMIT, Nitte 26


Asynchronous - True or False?:

Serverrequests should be sent asynchronously.


The async parameter of the open() method should be set to true:

xhttp.open("GET", "ajax_test.asp", true);

By sending asynchronously, the JavaScript does not have to wait for


the server response, but can instead:
execute other scripts while waiting for server response

deal with the response after the response is ready

03/20/23 Dept of CSE, NMAMIT, Nitte 27


The responseText Property

The data sent back from the server can be retrieved with the
responseText property.

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}

03/20/23 Dept of CSE, NMAMIT, Nitte 28


XMLHttp GET Requests

 In the main HTML page, the basic setup is this:

<p>Customer Id : <input type=“text” id=“txtCustomerId” value=“ ” />


</p>
<p><input type=“button” value=“Get Customer Info”
onClick=“requestCustomerInfo ( )” /> </p>
<div id=“divCustomerInfo”> </div>

03/20/23 Dept of CSE, NMAMIT, Nitte 29


function requestCustomerInfo ( )
{
var sId= document.getElementById(“txtCustomerId”).value;
var oXmlHttp=zXmlHttp.createRequest ( );
oXmlHttp.open(“get”, ”GetCustomerdata.php?id=“ + sId, true);
oXmlHttp.onready = function ( )
{
if (oXmlHttp.readyState == 4)
{
if (oXmlHttp.status==200)
{
displayCustomerInfo(oXmlHttp.responseText);
}
else
{
displayCustomerInfo(“An Error occurred: “ + oXmlHttp.statusText);
}
}
};
oXmlHttp.send(null);

03/20/23 Dept of CSE, NMAMIT, Nitte 30


 The server side code GetCustmerData.php have the following form:
<?php
header(“Content-Type: text/plain”);
//remaining php code goes here
….
echo $sInfo;
?>

03/20/23 Dept of CSE, NMAMIT, Nitte 31


Summary of Steps to process Async requests

1.Create the XMLHttpRequest object.


2.Set the readystatechange event to trigger a specific function

3.Check the readystate property to see if data is ready. If it is not ready


it rechecks after periodic intervals.
4.Follows the next step if the state is ready

5.Opens the request

6.Sends the request

7.Continues the processing until response is received.

03/20/23 Dept of CSE, NMAMIT, Nitte 32


Advantages and disadvantages of XMLHttp…

 Code written is much cleaner and the intent of the code is much
more apparent than using numerous callback functions with hidden
frames

 We have access to request and response headers as well as HTTP


status codes

03/20/23 Dept of CSE, NMAMIT, Nitte 33


 The other option for creating cross-browser XMLHttp objects
is to use a library that already has cross-browser code written

 This library defines a single function for the creation of


XMLHttp objects:

var oXmlHttp = zXmlHttp.createRequest ( );

 zXMLHttp class is used to create cross browser XMLHttp


objects using a common interface.
 Method createRequest creates an XMLHttp object.

03/20/23 Dept of CSE, NMAMIT, Nitte 34


Ajax Principles
Following principles make web application as a good AJAX
application

Minimal Traffic – Ajax applications should send and receive as little


information as possible to and from the server.
AJAX can minimize traffic b/n client and server by not sending
unnecessary info and images.

No surprises (Interaction models) – Ajax applications typically


introduce different user interaction models than traditional web
applications.
As opposed to the web standard of click-and-wait, some Ajax
applications use other user interface paradigms such as drag-and-drop
or double clicking

03/20/23 Dept of CSE, NMAMIT, Nitte 35


 Established Conventions – Borrow user interaction models heavily
from traditional web applications and desktop applications so there is
a minimal learning curve. (Uses established conventions for user
interactions via pages hence minimal learning curve).

 Accessibility – Don’t program yourself into a corner so that an


unexpected new audience will be completely locked out. (Consider
primary users of site and develop)

 Avoid Entire Page Downloads – All server communication after the


initial page download should be managed by the Ajax Engine. Don’t
ruin the user experience by downloading small amounts of data in
one place, but reloading the entire page in others

 User First – Design the Ajax application with the users in mind
before anything else. Try to make common use cases easy to
accomplish the task

03/20/23 Dept of CSE, NMAMIT, Nitte 36


Process flow diagram consists of following
steps:
1. The user triggers an event, for example by releasing a key when
typing a name. This results in a JavaScript call to a function that
initializes XMLHttpRequest object.

2. The XMLHttpRequest object is configured with a request parameter


that includes the ID of the component that triggered the event and any
value that the user entered.
The XMLHttpRequest object then makes an asynchronous request to
the web server.

03/20/23 Dept of CSE, NMAMIT, Nitte 37


3. On the web server, an object such as a servlet or listener handles the
request.
Data is retrieved from the data store and a response is prepared
containing the data in the form of XML document.

4. Finally the XMLHttpRequest object recieves XML data using a call


back function, processes it, updates HTML DOM to display page
containing new data.

03/20/23 Dept of CSE, NMAMIT, Nitte 38


Thank You…

03/20/23 Dept of CSE, NMAMIT, Nitte 39

You might also like