Ajax2

Ajax2.html  [download]

<html>
<head>

<title>Comp 86 example Ajax2</title>
<!-- Reply in XML not text -->

<script type="text/javascript">

var xmlhttp

// Called on key up
function getReply (inp) {
      // Get an xmlhttp object
      xmlhttp = CreateXMLHttpRequest ()
      if (xmlhttp==null) {
      	alert ("Your browser does not support XMLHTTP!");
      	return;
      }

      // Make the call
      xmlhttp.onreadystatechange = stateChanged;
      xmlhttp.open ("GET", "Ajax2.php?input=" + escape(inp), true);
      xmlhttp.send (null);
}

// Callback from xmlhttpobject
function stateChanged () {
      if (xmlhttp.readyState==4) {
	var response =  xmlhttp.responseXML; //*1 Take the response in XML not text

	document.getElementById("outputText").innerHTML =  //*3 Plug returned values into HTML
	    response.documentElement.getElementsByTagName("outputText")[0].childNodes[0].nodeValue; //*2 Parse XML
	document.getElementById("server").innerHTML = //*3
	    response.documentElement.getElementsByTagName("server")[0].childNodes[0].nodeValue; //*2
	document.getElementById("time").innerHTML = //*3
	    response.documentElement.getElementsByTagName("time")[0].childNodes[0].nodeValue; //*2
      }
}

// For compatibility with different browsers
function CreateXMLHttpRequest () {
	try {
		// Firefox, Safari, ...
		ans = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			// Newer IE
			ans = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				// Older IE
				ans = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				ans = null;
			}
		}
	}
	return ans;
}

</script> 
</head>

<body>

<i>Your input: </i>
<input type="text" id="inputText" onkeyup="getReply(this.value)" />

<p>
<i>Output: </i><span id="outputText"></span>
</p>

<hr>

<p>
The time on server
<b><span id="server"></span></b>
is now
<b><span id="time"></span></b>
</p>

</body>
</html>

Ajax2.php  [download]

<?php
// Server script called by Ajax2.html

header ("Content-Type: text/xml");
print '<?xml version="1.0" encoding="utf-8"?>';
?>

<main>
<outputText>
<?php print strrev($_GET[input]); ?>
</outputText>

<time>
<?php print date("r"); ?>
</time>

<server>
<?php print $_SERVER["SERVER_NAME"]; ?>
</server>

<other>You can have other items here, we will ignore them</other>
</main>

Ajax2.cgi  [download]

#!/bin/sh
# Server script for Ajax2.html
# WORKS OK BUT NOT ACTUALLY USED,
# just to show what Ajax2.php does if you don't know php

echo "Content-Type: text/xml"
echo ""

echo "<?xml version='1.0' encoding='ISO-8859-1'?>"
echo "<main>"

echo "<outputText>"
# Get our CGI arg and reverse it
echo "$QUERY_STRING" | sed -e 's/.*input=//' -e 's/&.*//' -e 's/%20/ /g' | rev
echo "</outputText>"

echo "<server>"
hostname
echo "</server>"

echo "<time>"
date
echo "</time>"

echo "<other>You can have other items here, we will ignore them</other>"
echo "</main>"