The HTML code for the link:
<a href='javascript:;' onClick='doAjaxRequest("ajaxexample.php?action=printSimpleMessage", "responseDiv");'>
Click here to receive a message from the server
</a>
<div id='responseDiv'>The server message will go here</div>
The Javascript Function (doAjaxRequest):
function doAjaxRequest(actionUrl, elemId) {
// MAKE NEW XMLHTTP OBJECT
var xmlHttp=null
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest()
}
catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
}
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request")
return
}
// WHAT TO DO WITH THE RESPONSE
xmlHttp.onreadystatechange=function() {
if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(elemId).innerHTML="processing, please wait..."
}
else if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(elemId).innerHTML=xmlHttp.responseText
}
}
// MAKE THE REQUEST
xmlHttp.open("GET",actionUrl,true)
xmlHttp.send(null)
}
The server side script:
<?
if(isset($_GET['action'])) {
$gaction = $_GET['action'];
if($action == 'printSimpleMessage') echo "Here is a message from the server";
exit;
}
?>