Programming in Ajax
• We consider a program that asks the user to click a button, fetches data from the server using Ajax techniques, and displays that data in the same Web page as the button – without refreshing the page.
November 25, 2010 2Mukesh N Tekwani, Mumbai
Programming in Ajax
November 25, 2010 3Mukesh N Tekwani, Mumbai
Programming in Ajax
November 25, 2010 4Mukesh N Tekwani, Mumbai
<body>
<h1>Fetching data with Ajax</h1>
<form>
<input type = "button" value = "Display Message"
onclick = "getData('http://localhost/AJAX/data.txt', 'targetDiv')">
</form>
<div id = "targetDiv">
<p>The data fetched will go here</p>
</div>
</body>November 25, 2010 5Mukesh N Tekwani, Mumbai
• The body of the page starts by displaying the original text in a <div> element
<div id = "targetDiv">
<p>The data fetched will go here</p>
</div>
November 25, 2010 6Mukesh N Tekwani, Mumbai
• There’s a button on this page. When the user clicks on the button, a JavaScript method named getData is called.
<form>
<input type = "button"
value = "Display Message"
onclick = "getData('http://localhost/AJAX/data.txt', 'targetDiv')">
</form>• The getData function is passed two strings:
November 25, 2010 7Mukesh N Tekwani, Mumbai
• The first string is:
onclick = "getData('http://localhost/AJAX/data.txt', 'targetDiv')">
• The getData function is passed two strings:1. The name of the text file data.txt to fetch from
the server, and
2. The name of the <div> element to display the fetched text in.
November 25, 2010 8Mukesh N Tekwani, Mumbai
Creating the XMLHttpRequest Object
• The code to create the XMLHttpRequest object is outside any function, so this code runs immediately as the page loads.
• We create a variable for this object XMLHttpRequestObject.var XMLHttpRequestObject = false;
This variable is initialized to the value ‘false’ so that the script can check later whether the variable was created.
November 25, 2010 9Mukesh N Tekwani, Mumbai
• The XMLHttpRequest object is part of the browser’s window object. So to check whether the XMLHttpRequest object is ready to use, we use the if statement.
• If XMLHttpRequest object is available, we can create the object as follows:
if(window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
}
XMLHttpRequest Object
November 25, 2010 10Mukesh N Tekwani, Mumbai
If we are working with Internet Explorer, we can create an XMLHttpRequest object like this:
else if (window.ActiveXObject)
{
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
XMLHttpRequest Object
November 25, 2010 11Mukesh N Tekwani, Mumbai
XMLHttpRequest Object
• Now we have an XMLHttpRequest object.• The properties and methods of the
XMLHttpRequest object for IE are as follows:
November 25, 2010 12Mukesh N Tekwani, Mumbai
XMLHttpRequest Object
• onreadystatechange – holds the name of the event handler that should be called when the value of the readystate property changes. In our example, it is function()
• readyState – holds the state of the request
November 25, 2010 13Mukesh N Tekwani, Mumbai
Checking to make sure we have the XMLHttpRequest Object
• The getData() function will be used to actually fetch the text data from the file
• We first check that there is a valid object with the statement if(XMLHttpRequestObject)
• If the object creation hadn’t worked, then this variable will hold a value ‘false’ and the condition would become false.
November 25, 2010 14Mukesh N Tekwani, Mumbai
Opening the XMLHttpRequest Object
• Now we have the XMLHttpRequestObject variable
• This object has a method called “open()”. We will use that method to use the URL we want.
• Syntax of open() method is:• open (“method”, “URL”, [,asyncFlag [,
“username” [, “password”]]])
November 25, 2010 15Mukesh N Tekwani, Mumbai
Opening the XMLHttpRequest Object
• Syntax of open() method is:• open (“method”, “URL”, [,asyncFlag [,
“username” [, “password”]]])• method – the HTTP method used to open the
connection such as GET, POST, PUT, HEAD• URL – the requested URL• asyncFlag – A boolean value indicating
whether the call is asynchronous or synchronous. Default is ‘true’ (asynchronous)
November 25, 2010 16Mukesh N Tekwani, Mumbai
Opening the XMLHttpRequest Object
• The URL we want to fetch is passed to the getData() function as the dataSource argument
• To open a URL we can use the GET, POST or PUT methods.
• But in Ajax, we will use GET to retrieve data and POST to send a lot of data to the server
XMLHttpRequestObject.open("GET", dataSource);
November 25, 2010 17Mukesh N Tekwani, Mumbai
Opening the XMLHttpRequest Object
• Now, XMLHttpRequestObject is ready to use the URL we have given. But it does not connect to that file.
• By default the connection to this file is made asynchronously. It means that this statement does not wait until the connection is made and the data is finished downloading
November 25, 2010 18Mukesh N Tekwani, Mumbai
How to handle Asynchronous Requests
• The XMLHttpRequest object has a property called onreadystatechange that lets you handle asynchronous loading operations.
• If we assign the name of a JavaScript function to this property, that function will be called each time the XMLHttpRequest object’s status changes.
November 25, 2010 19Mukesh N Tekwani, Mumbai
How to handle Asynchronous Requests
• XMLHttpRequestObject.onreadystatechange = function()• We have used a shortcut to assign a JavaScript function to
the onreadystatechange property.• We have created an anonymous function because the
function does not have any name. Such a function is created on the fly, just by using the keyword function(). Then we define the body of this function in curly braces:
November 25, 2010 20Mukesh N Tekwani, Mumbai
How to handle Asynchronous Requests
XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
• This new anonymous function will be called when the XMLHttpRequestobject undergoes some change e.g., when downloading data
November 25, 2010 21Mukesh N Tekwani, Mumbai
How to handle Asynchronous Requests
• The XMLHttpRequestobject has 2 properties that are important for us:
• readyState property– readyState property that tells us how the data downloading is
progressing. – The readyState property can have these values:
• 0 – uninitialized• 1 – loading• 2 – loaded• 3 – interactive• 4 – complete
• We have used the value 4, which means the data is downloadedNovember 25, 2010 22Mukesh N Tekwani, Mumbai
How to handle Asynchronous Requests
• The XMLHttpRequestobject has 2 properties that are important for us:
• status property– This property that tells us the status of the download itself.– It is the standard HTTP status code that the browser got for the URL
you supplied.– The possible values of status are:
• 200 – all OK• 400 – Bad request• 403 – Forbidden• 404 – Not found• 408 – request time out• 414 – Requested URL too long
November 25, 2010 23Mukesh N Tekwani, Mumbai
How to Handle Asynchronous Requests
Now let us see the same statement again:
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
• It means we are checking that the data has been downloaded completely (readyState = 4) and everything went ok with the request to the server (status = 200)
November 25, 2010 24Mukesh N Tekwani, Mumbai
Getting the Data into the Web page
• The data has been fetched from the server. Now to get the data on the Web page we use one of these techniques:– If we want to treat the data as standard text, we use the
object’s responseText property.– If the data is in XML format, we can use the
responseXML property.
• To make the test appear on the page, we assign that text to the <div> element whose ID is targetDiv. This ID was passed to the getData() function.
November 25, 2010 25Mukesh N Tekwani, Mumbai
Getting the Data into the Web page
• How to connect to the server to get the response?– We use the send() method. – When we are using the GET method, we send a value of null to connect to the server and request the data using the XMLHttpRequest object.
XMLHttpRequestObject.send(null);• The send() method actually downloads the data so
that the anonymous function can handle that data.
November 25, 2010 26Mukesh N Tekwani, Mumbai
Absolute vs Relative URLs• If the index.html file and the data file data.txt are in
the same directory we can use the relative URL as follows:
‘data1.txt‘• If these files are in different folders, we must use
absolute URL, where we give the complete path of the files:
http://localhost/AJAX/data1.txt
November 25, 2010 27Mukesh N Tekwani, Mumbai
Top Related