WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Example - AJAX Live Search

AJAX provides users with a friendlier and more interactive search experience.


AJAX Live Search

In the example below, we will demonstrate a real-time search, and get search results as you type data.

Real-time search has many advantages over traditional search:

  • When you type data, matching results are displayed
  • Filter results as you continue typing
  • If the result is too few, you can get a wider range by deleting characters

Enter "HTML" in the text box below, and search for pages that contain HTML:

The results in the example above are in an XML file (links.xml)Search. To keep this example small and simple, we only provide 6 results.


Example explanation-HTML page

When the user types a character in the input box above, the "showResult ()" function is executed. This function is triggered by the "onkeyup" event:

<html>
<head>
<script>
function showResult(str)
{
    if (str.length==0)
    { 
        document.getElementById("livesearch").innerHTML="";
        document.getElementById("livesearch").style.border="0px";
        return;
    }
    if (window.XMLHttpRequest)
    {//IE7+, Firefox, Chrome, Opera, Safari Browser execution
        xmlhttp=new XMLHttpRequest();
    }
    else
    {//IE6, IE5 Browser execution
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
            document.getElementById("livesearch").style.border="1px solid #A5ACB2";
        }
    }
    xmlhttp.open("GET","livesearch.php?q="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

Source code explanation:

If the input box is empty (str.length == 0), the function clears the contents of the livesearch placeholder and exits the function.

If the input box is not empty, showResult () performs the following steps:

  • Creating an XMLHttpRequest object
  • Create a function to be executed when the server response is ready
  • Send a request to a file on the server
  • Please note the parameter (q) added to the end of the URL (including the content of the input box)

PHP file

The above server page called via JavaScript is a PHP file named "livesearch.php".

The source code in "livesearch.php" searches the XML file for titles that match the search string and returns the results:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//From URL The value of parameter q in
$q=$_GET["q"];

//Find data from xml file if q parameter is present
if (strlen($q)>0)
{
    $hint="";
    for($i=0; $i<($x->length); $i++)
    {
        $y=$x->item($i)->getElementsByTagName('title');
        $z=$x->item($i)->getElementsByTagName('url');
        if ($y->item(0)->nodeType==1)
        {
            //Find a link that matches your search
            if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
            {
                if ($hint=="")
                {
                    $hint="<a href='" . 
                    $z->item(0)->childNodes->item(0)->nodeValue . 
                    "' target='_blank'>" . 
                    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
                }
                else
                {
                    $hint=$hint . "<br /><a href='" . 
                    $z->item(0)->childNodes->item(0)->nodeValue . 
                    "' target='_blank'>" . 
                    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
                }
            }
        }
    }
}

//If not found, return "no suggestion"
if ($hint=="")
{
    $response="no suggestion";
}
else
{
    $response=$hint;
}

//Output result
echo $response;
?>

If JavaScript sends any text (i.e. strlen($q) > 0),Will happen:

  • Loading XML files into new XML DOM objects
  • Iterate over all <title> Element to find the text passed by JavaScript
  • Set the correct URL and title in the "$ response" variable. If more than one match is found, all matches are added to the variable.
  • If no match is found, set the $ response variable to "no suggestion".