Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP AJAX Live Search Example

PHP Example - AJAX Live Search


AJAX can provide users with a friendlier and more interactive search experience.


AJAX Live Search

In the example below, we will demonstrate a live search that returns results as you type.

Live search has many advantages over traditional search:

Enter "HTML" in the text box below to search for pages containing HTML:

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


Example Explanation - HTML Page

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















Source code explanation:

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

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


PHP File

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

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



load("links.xml");



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



// Get the value of parameter q from the URL

$q=$_GET["q"];



// If the q parameter exists, search for data in the xml file

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 links matching the search

            if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))

            {

                if ($hint=="")

                {

                    $hint="" . 

                    $y->item(0)->childNodes->item(0)->nodeValue . "";

                }

                else

                {

                    $hint=$hint . "
" .                     $y->item(0)->childNodes->item(0)->nodeValue . "";                 }             }         }     } } // 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), the following happens: