Ajax1

Ajax1.html  [download]

<html>
<head>

<title>Comp 86 example Ajax1</title>
<!-- Using asynchronous server call -->

<script type="text/javascript">

var xmlhttp

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

      // Make the call
      xmlhttp.onreadystatechange = stateChanged; //*2 Callback for when server responds
      xmlhttp.open ("GET", "Ajax1.php?input=" + escape(inp), true); //*1
      xmlhttp.send (null); //*1
}

// Callback from xmlhttpobject
function stateChanged () { //*2
      if (xmlhttp.readyState==4) { //*2
	    var response = xmlhttp.responseText; //*3 Parse response and use it in our HTML

	    // Separate out the 3 lines
	    var lines = response.split("\n"); //*3

	    document.getElementById("outputText").innerHTML = lines[0]; //*3
	    document.getElementById("server").innerHTML = lines[1]; //*3
	    document.getElementById("time").innerHTML = lines[2]; //*3
      }
}

// 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>

Ajax1.php  [download]

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

print strrev($_GET[input]) . "\n";
print $_SERVER["SERVER_NAME"] . "\n";
print date("r") . "\n";
?>

Ajax1.cgi  [download]

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

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

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

# Return the other info
hostname
date