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.
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.
Let’s start by creating our index HTML page:
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 arrayif (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 matchesecho ($matches == "") ? 'no match found' : $matches;?>
Create a JavaScript file:
function Run_Func(str){if (str.length == 0){ //exit function if nothing has been typed in the textboxdocument.getElementById("txtName").innerHTML="";return;}if (window.XMLHttpRequest) {// if found create an XML HTTP requestxmlhttp=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:
Free Resources