AJAX - The Complete Reference

(avery) #1

76 Part I: Core Ideas


<script type="text/javascript">
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}

function sendRequest()
{
var responseOutput = document.getElementById("responseOutput");
responseOutput.style.display = "";
var xhr = createXHR();
if (xhr)
{
xhr.open("GET", "http://ajaxref.com/ch3/helloworld.php", false);
xhr.send(null);
responseOutput.innerHTML = "<h3>reponseText</h3>" + xhr.responseText;
}
}

window.onload = function ()
{
document.requestForm.requestButton.onclick = function () { sendRequest(); };
};
</script>
</head>
<body>
<form action="#" name="requestForm">
<input type="button" name="requestButton" value="Send Synchronous Request" />
</form>
<br />
<div id="responseOutput" class="results" style="display:none;"> </div>
</body>
</html>

The PHP code that responds to this request is quite simple and the only details have to
do with the cache control issues that will be discussed shortly.

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");

$ip = GetHostByName($_SERVER['REMOTE_ADDR']);
echo "Hello user from $ip it is ". date("h:i:s A"). " at the Ajaxref.com server";
?>

Of course, this previous example isn’t really Ajax if you are a stickler for the precise
meaning of the acronym as it used synchronous communication and no XML; it was Sjat
(Synchronous JavaScript and Text), if you want to be precise. All jesting aside, it is important
Free download pdf