JavaScript XMLHttpRequest Object Tutorial
Here is an example of XMLHttpRequest Object using:
PHP Code:
function moveCalendar(month, year)
{
var xmlHttp;
// Create xmlHttp Object
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
// Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
// Event Handler - EventListener
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) // 4: The Request is complete
{
document.getElementById('calendar').innerHTML = xmlHttp.responseText; // Response
}
}
// Request
xmlHttp.open("GET", "/modules/mod_calendar.php?month="+month+"&year="+year, true);
xmlHttp.send(null);
}
</div> Stated above example tries to create an XMLHttpRequest Object. If successfull, a function is triggered by XMLHttp state change which reacts to the request represented by last two lines of the code. PHP script (calendar module in this case) expects a GET requests and returns the HTML code of the calendar portion (a month) specified by request (month and year). This returned code is then pushed into the page code by setting the HTML DOM property innerHTML to the value of XMLHttp response.
But what is this complicated manner good for? The main advantage is that by using XMLHttpRequest Object you don’t have to reload whole page when trying to retrieve some information. There’s just small part of page changed which result in very fast, dynamic effect of updating the data. Also, pushing a data to database is carried out much effective in case of XMLHttpRequest Object use.
Coding a script using XMLHttpRequest Object can be done manually (every action is coded separately) or you can use one of the frameworks which incorporates AJAX or offers nice interface to your existing PHP code. I personally, prefer the second type, so I use the
xAJAX library where an XMLHttpRequest Object should be convenient. The goal of the
xAJAX object is that you don’t have to change anything in your existing application source code. Just load the library, create object, register the function or class you want to handle by AJAX and that’s it!
Finally, there should be noted that from security reasons the XMLHttpRequest Object works
within a domain only! It means that call of some location outside the domain leads to security error like this:
Error: uncaught exception: [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "http://www.testfiles.loc/js/testfile.js Line: 43"]
I hope, this brief intro into the XMLHttpRequest Object gave you at least basic overview of AJAX technology.