Ajax Notes

AJAX = Asynchronous JavaScript and XML.

update parts of a web page, without reloading the whole page.

  • XML (often used as the format for transferring data)

AJAX REQUEST

XMLHttpRequest object is used to exchange data with a server behind the scenes.

Get Request

xmlhttp.open(“GET”,”demo_get2.asp?fname=Henry&lname=Ford”,true);
xmlhttp.send();

Post Request

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

AJAX RESPONSE

ResponseText Property get the response data as a string

document.getElementById(“myDiv”).innerHTML=xmlhttp.responseText;

responseXML Property

Request the file cd_catalog.xml and parse the response:

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;

 

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically

each time the readyState property changes

readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: “OK”
404: Page not found

 

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}

Using a Callback Function

A callback function is a function passed as a parameter to another function.

If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.

The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):

 

 

 

Example

function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
Facebooktwittergoogle_plusredditpinterestlinkedinmail
1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 4.92 out of 5)
Loading...