What is the PHP model in AJAX?

AJAXAsynchronous JavaScript And XML is used for creating asynchronous web applications. It is deployed on the client-side and makes use of several web technologies. AJAX has made it easier to asynchronously send and retrieve data from a server without interfering with the existing page’s display and functionality.

AJAX is not a programming language – it requires a built-in browser with a XMLHttpRequest object that requests data from the server. It also uses JavaScript and HTML DOM to display data.

Creating an AJAX PHP model

The combination of PHP and AJAX is used to create simple search engines. Let’s try to create one that will give you suggestions based on your input.

Step 1

Let’s start by creating our index HTML page:

Step 2

Create the PHP framework choc.php to store an array of chocolates that we want to view on our screen:

<?php
// my chocolate array
$chocolates = array("Hersheys", "Twix", "Snickers", "Hopje", "Humbugs") ;
// get the name input from user
$name = $_GET["name"];
if (strlen($name) > 0) {
// matches store our value to be returned.
$matches = "";
for ($i = 0; $i < count($chocolates); $i++) {
// compare the input with values in array
if (strtolower($name) == strtolower(substr($chocolates[$i], 0, strlen($name))))
{
if ($matches == "")
{
// add the string from the index
$match = $chocolates[$i];
}
else
{
// append to the matches
$matches = $matches . " , " . $chocolates[$i];
}
}
}
}
// if no matches
echo ($matches == "") ? 'no match found' : $matches;
?>

Step 3

Create a JavaScript file:

function Run_Func(str){
if (str.length == 0)
{ //exit function if nothing has been typed in the textbox
document.getElementById("txtName").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// if found create an XML HTTP request
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("my_matches").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","choc.php?name="+str,true);
xmlhttp.send();
}

Now, if, for example, you enter the character H, you will get:

Result
Result

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved