$customer_id=$_POST['customer_id'];
$var=array(003=>"Jim",005=>"Ron",007=>"Kim");
// Array from which the customer name is to be taken
if(array_key_exists($customer_id,$var))
{ echo "Name of the customer: $var[$customer_id]";}
else {echo " No customer name available";}
As you can see in the above code, the script collects the customer_id and then if the id is present inside the (PHP) array then the name of the corresponding customer is returned, otherwise a message saying customer name not there is returned to calling html page. We used array_key_exists() to search for the customer id.
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>(Type a title for your page here)</title>
<script language="javascript" type="text/javascript">
var ajrequest= null;
try {
ajrequest= new XMLHttpRequest();
} catch (trymicrosoft) {
try {
ajrequest= new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
ajrequest= new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
ajrequest= null;
}
}
}
if (ajrequest== null)
alert("Error creating request object!");
///////////////////////////////
function stateChanged()
{
if(ajrequest.readyState==4)
{
document.getElementById("txtHint").innerHTML=ajrequest.responseText;
}
}
/////////////////////////////////
function getFormData(myForm) {
var myParameters = new Array();
for (var i=0 ; i < myForm.elements.length; i++) {
var sParam = encodeURIComponent(myForm.elements[i].name);
sParam += "=";
sParam += encodeURIComponent(myForm.elements[i].value);
myParameters.push(sParam);
}
return myParameters.join("&");
}
////////////////////////////////////////////
function getInfo(){
var url="code.php";
var myForm = document.forms[0];
var parameters=getFormData(myForm);
ajrequest= new XMLHttpRequest();
//var ajrequest= newrequest();
ajrequest.onreadystatechange=stateChanged;
ajrequest.open("POST", url, true);
ajrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajrequest.send(parameters) ;
}
////////////////////////////////
</script>
</head>
<body>
<form name="myForm" >
Customer ID: <input type=text size=3 name=customer_id onBlur=getInfo();><br>
<input type=submit value=Submit>
</form>
<div id="txtHint"><b>Customer info will be listed here.</b></div>
</body>
</html>
Download the zip file ( both code.htm & code.php )
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.