Universal Ajax Script

This Ajax script can be easily used in any web page.   In this example we will be calling a PHP script to echo what is typed in.  Usually, you grab some data from a database depending on input -  a simple search.

This part goes in the <head> tag of your page.

<script language="JavaScript">
<!--
//Simple Ajax Call by Logan Stewart (website-whisperer.com)
var xmlHttp
//
function showHint(script_to_call, output_div_name, var_1_key, var_1_val, var_2_key, var_2_val){
output_to = output_div_name;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
 alert ("Browser does not support HTTP Request");
 return;
 }
var url=script_to_call;
url=url+"?"+var_1_key+"="+escape(var_1_val);
url=url+"&"+var_2_key+"="+escape(var_2_val);
url=url+"&random_number="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var out_to_div = findObj(output_to);
 out_to_div.innerHTML=xmlHttp.responseText ;
 }
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 try
 {
 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch (e)
 {
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 }
return xmlHttp;
} 

function findObj(theObj, theDoc)
{
 var p, i, foundObj;
 if(!theDoc) theDoc = document;
 if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
 {
 theDoc = parent.frames[theObj.substring(p+1)].document;
 theObj = theObj.substring(0,p);
 }
 if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
 for (i=0; !foundObj && i < theDoc.forms.length; i++)
 foundObj = theDoc.forms[i][theObj];
 for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
 foundObj = findObj(theObj,theDoc.layers[i].document);
 if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
 return foundObj;
}
//-->
</script>

This next part (the form – although don’t use <form>tags) goes somewhere in the <body>.

<input type="text" name="what_to_look_for">
<input type="button" value="go" onClick="showHint('lookup.php', 'output_here', 'what_to_look_for', what_to_look_for.value, 'unused_key_in_this_example', 'unused_value_in_this_example')">

This next part (also placed in the body) is where the answer from the PHP script will go.

<div id="output_here">This text will be replaced by the answer</div>

Finally, we need some PHP to do the work.  This will go on a different page called lookup.php.

<?php
// connect to your database and do look-up. Since This is beyond the scope of this script, we will just echo the input.

foreach($_GET as $key=>$value){echo "key=$key, value=$value<br>";}

?>