File that displays page with everything except the "data" content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<title>AJAX Test</title>
<script type="text/javascript">
/*
AJAX function to request data from URL, and update innerHTML content
of HTML element specified by supplied id
*/
function ajaxFunction(url,id)
{
/* usual stuff to create xmlHttp object */
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Could not display some data as your browser does not support AJAX.");
return false;
}
}
}
/* when data received, update contents of specified HTML element */
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(id).innerHTML = xmlHttp.responseText;
}
}
/* display "loading" message before requesting new data */
document.getElementById(id).innerHTML = '<p>Loading, please wait....</p>';
/* Send request */
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
</script>
</head>
<body onload="ajaxFunction('ajax.php?data=This+is+a+test', 'example');">
<div id="example">
<p>Loading...please wait...<p>
</div>
</body>
</html>
The "ajax.php" file called by the above to actually return the content:
<?php
// simulate processing delay:
sleep(10);
// return HTML to be output (this is where you would do DB query/output stuff:
?>
<h1>Success!</h1>
<p>You requested data for '<?php
echo (isset($_GET['data'])) ? $_GET['data'] : 'NOTHING';
?>'</p>