Simple AJAX Example
AJAX is a way of using Javascript, Dynamic HTML and the XMLHttpRequest (IE uses the ActiveX object “Microsoft.XMLHTTP”) object to perform HTTP GETs and POSTs. The results (return value(s)) are interpreted and through DHTML the source page can be updated. The great part is the user is none the wiser to what happened - the behavior simulates a true thick-client experience, which is the holy grail in web application development.
Below is a very simple example that utilizes a PHP script to print out the remote user’s IP address.
View a running example here.
HTML page:
This is the HTML page with the necessary JavaScript functions that perform the AJAX functionality and also the code that updates the page.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajaxsicle - Sample #1</title>
<meta name="author" content="Kevin Hillabolt">
<script language="javascript">
var xmlhttp
function getIPAddress() {
document.getElementById("ipaddress").innerHTML = "Wait...";
if (typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = updateIPAddress;
xmlhttp.open("GET","http://www.ajaxsicle.com/samples/1/getip.php", true);
xmlhttp.send(null);
}
function updateIPAddress() {
if (xmlhttp.readyState == 4) {
var xmlDoc = xmlhttp.responseXML;
var nds = xmlDoc.getElementsByTagName("remote");
var nd = nds[0];
document.getElementById("ipaddress").innerHTML = "Your IP Address is: " +
nd.attributes[0].nodeValue;
xmlhttp = null;
}
}
</script>
</head>
<body>
<h1>A simple Ajax example</h1>
<P>This example demonstrates Asynchronous JavaScript and XML.</P>
<h2 id="ipaddress">Click the button below...</h2>
<p><input onclick="getIPAddress()" type="button"
value="Click to get your IP Address"></p>
</body>
</html>
PHP Script
This is the PHP script that the HTML page calls. This script could have easily been implemented with any language.
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="utf-8"?'.">";
echo '<remote ip="';
echo getenv(REMOTE_ADDR);
echo '" />';
?>
Note: pay special attention to the line “Content-Type: text/xml”. You must specify this mime type, otherwise the XMLHttpRequest will not work properly.
