This is an example of how to do it, you will have to change it for your own needs:
index.php:
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Happy Eater</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput"></div>
</body>
</html>
The index takes an input field with an ID (this is where you type) the output is the div with ID underInput.
JavaScript File:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Cant create that object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
}
else
{
alert('Something Went Wrong!');
}
}
}
the javascript file checks the input and then sends that information to the background php file which does the work in php and returns the result in XML format. The javascript file then takes the result and updates the index.php. after the function is called when the page is loaded, it keeps running once every second (can be changed) which will give the impression that its updating live so you dont have to click outside the text box for the field to update.
Background PHP File:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'loaf', 'ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food=='')
echo 'Enter a food you idiot';
else
echo 'Sorry We Dont Sell '.$food.'!';
echo '</response>';
?>
the background php file returns everything in XML format.
This above method is similar to how google have their live search update.
-*This code is taken from a The New Boston Tutorial