Hi
I always break my AJAX down into 3 areas.
1) A function for the GetXmlHttpObject()
2) A function which POST/GET's the data to/from a PHP script
3) A function which detects the onreadystatechange event
So, at the top of my script I would have the following:
function GetXmlHttpObject(handler) {
var objXmlHttp=null;
if (window.ActiveXObject) // ActiveX version
{
try
{
objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
objXmlHttp.onreadystatechange=handler;
return objXmlHttp;
}
catch(e)
{
alert("Error. Scripting for ActiveX might be disabled");
return;
}
}
else if (window.XMLHttpRequest) // Object of the current windows
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload=handler;
objXmlHttp.onerror=handler;
return objXmlHttp;
}
}
Then I create my AJAX function. Below is a very simple example of posting values to a PHP script called myphpscript.php:
function myFunction(value1, value2, value3) {
var url = "/includes/ajaxfunctions/myphpscript.php";
var info = "vala="+value1+"&valb="+value2+"&valc="+value3;
xmlHttp = GetXmlHttpObject(myFunctionDone);
xmlHttp.open("POST", url , true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", info.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(info);
}
And then you need to detect the response and act upon it:
function myFunctionDone() {
if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById('ajax-container').innerHTML = "Loading...";
}
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
if (xmlHttp.responseText == 'yes') {
displaySomethingElse();
}
}
}
WItihin that last function you will see that the innherHTML of the DIV 'ajax-container' will be set to say 'loading...' until the response from thr PHP code is complete and withint the PHP script, I echo the word 'yes'. When the AJAX detects this, it moves onto readystate = 4 and I then run another function which possibly loads a script which displays data.
I hope that helps.