Ajax 1
Ajax 1
xmlhttp=new XMLHttpRequest(); }
else { // code for IE6, IE5
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP"); }
To send request
We send a request by the following two methods:
1.open() 2. send()
Description for open and send methods:
open(method,url,async)
• method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)
• Sends the request to the server.
Using response of server
• To get the response from a server there are
following two methods.
1. responseText : get the response data as a
string
2. responseXML : get the response data as
XML data
• The responseText and responseXML are two
properties of XMLHttpRequest object.
Contd..
Syntax for responseText
document.getElementById("scanf_Div").innerHTML=xmlhttp.r
esponseText;
Syntax for responseXml
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("tag_for_which_you_requ
est_in_xml_file");
for (i=0;i<x.length;i++)
{ txt=txt + x[i].childNodes[0].nodeValue + "<br>";}
document.getElementById("scanf_div").innerHTML=txt;
The XMLHttpRequest Object
• Base object for AJAX used to make connections, send
data, receive data, etc.
• Allows your javascript code to talk back and forth
with the server all it wants to, without the user really
knowing what is going on.
• Available in most browsers but called different things
Object Creation
• variable=new XMLHttpRequest();
(or)
• variable=new
ActiveXObject("Microsoft.XMLHTTP");
The XMLHttpRequest Object
• Methods
– abort()
• cancel current request
– getAllResponseHeaders()
• Returns the complete set of http headers as a string
– getResponseHeader(“headername”)
• Return the value of the specified header
– open(“method”, “URL”, async, “uname”, “passwd”)
• Sets up the call
– setRequestHeader(“label”, “value”)
– send(content)
• Actually sends the request
The XMLHttpRequest Object
• Properties
– onreadystatechange
• Event handler for an event that fires at every state change
– readyState
• Returns the state of the object
– responseText
• Returns the response as a string
– responseXML
• Returns the response as XML - use W3C DOM methods
– status
• Returns the status as a number - ie. 404 for “Not Found”
– statusText
• Returns the status as a string - ie. “Not Found”
Sample Code
<html>
<head>
<script>
function loadXMLDocument()
{
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome,
Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
Contd..
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{document.getElementById("scanf_div").innerHTML=xmlhttp.res
ponseText; } }
xmlhttp.open("GET","ajaxexample.php",true);
xmlhttp.send();}
</script>
</head>
<body> <h2>SCANFTREE</h2><button type="button"
onclick="loadXMLDocument()">Click</button><span
id="scanf_div"></span>
</body></html>
Handling Server Responses
• When the server responds, your callback method will
be invoked.
– It is called at various stages of the process
– Test readyState
function updatePage()
{
if (request.readyState == 4) {
if (request.status == 200) {
// Handle the response
} else
alert("status is " + request.status);
}
}
HTTP Ready States
• 0: The request is uninitialized
– Before calling open()
• 1: The request is set up, but hasn’t been sent
– Before calling send()
• 2: The request is sent and is being processed
– Sometimes you can get content headers now
• 3: The request is being processed
– The server hasn’t finished with its response
• 4: The response is complete
readyState
readyState
• a property that holds status of
XMLHttpRequest
• It holds the status of the XMLHttpRequest.
Changes from 0 to 4.
Onreadystatechange
• An event which is triggered every time
readystate changes
readyState Value Meaning Description
The XHR has been instantiated, but
0 Uninitialized the open() method has not been
called yet
new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport)
{
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function()
{
alert('Something went wrong...')
}
});
Prototype Example
<html>
<head>
<title>Testing Prototype</title>
<script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
<script>
function getProducts()
{
new Ajax.Updater('products', 'products.html', { method: 'get' });
}
</script>
</head>
<body>
<h2>Our fantastic products</h2>
<div id="products"><a href = "#" onClick="getProducts();">(fetch product list ...)</a></div>
</body>
</html>