Page Content

Tutorials

What is AJAX Live Search With Code Examples

What is AJAX Live Search?

While the “AJAX Live Search,” they describe functionality that aligns with this concept. A “Live Search” typically refers to a search feature where suggestions or results appear dynamically as a user types into a search box, without requiring a full page reload. This is achieved using AJAX.

AJAX stands for Asynchronous JavaScript and XML. It is a technique that allows JavaScript to communicate with a web server and update parts of a web page without reloading the entire page. This asynchronous nature is key to creating a smoother user experience compared to traditional form submissions which require a full page refresh. In modern web development, AJAX commonly uses JSON or HTML data instead of XML.

As a user inputs into a search box, AJAX Live Search, a web development approach, provides search results or suggestions without requiring a page reload. The user experience becomes more responsive and interactive as a result.

AJAX is not a programming language in and of itself. Usually, it combines server-side programming, such PHP, data transfer (formerly XML, but more frequently HTML or JSON), and client-side JavaScript programming. In AJAX apps, items are also presented using XHTML and CSS. In 2003, “AJAX” Asynchronous JavaScript and XML was introduced. In spite of this, HTML or JSON are frequently used in place of XML in contemporary AJAX applications.

Using AJAX to implement a live search function requires several essential components:

  • A search query entered by the user in an HTML input form.
  • Client-side JavaScript that sends an asynchronous request to the server after detecting user input (for example, by utilising the onkeyup event). Usually, the XMLHttpRequest object handles the main portion of this client-server connection.
  • A server-side script that receives the search query, runs a search (for example, against an array or XML data), and returns the results. This script is frequently built in PHP. PHP is frequently used for processing user input from web forms and server-side scripting.
  • The client-side JavaScript uses the server’s response to dynamically change a certain section of the page’s HTML document without reloading the entire page.

The following code samples, which are derived from demonstrate how this operates:

Example 1: Basic Hint Search in AJAX

As the user types, this sample offers suggestions.

HTML: Has a span> to show hints and an input field. The JavaScript showHint function is triggered by the onkeyup event.

<p><b>Search your favourite tutorials:</b></p>
<form>
    <input type = "text" onkeyup = "showHint(this.value)">
</form>
<p>Entered Course name: <span id="txtHint"></span></p>

JavaScript: The showHint method starts an asynchronous GET call to a PHP script (php_ajax.php) using the input value as a query parameter, generates an XMLHttpRequest object, specifies how to handle the server’s response (onreadystatechange), and then delivers the request. The innerHTML of the txtHint span is updated upon successful reception of the response (readyState 4, status 200).

Example:

function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest(); // 
        xmlhttp.onreadystatechange = function() { // 
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // 
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText; // 
            }
        }
        xmlhttp.open("GET", "php_ajax.php?q=" + str, true); // true for asynchronous 
        xmlhttp.send(); // 
    }
}

An array of names is contained in PHP (php_ajax.php). The search query ($_REQUEST[“q”] or $_GET[“q”]) is retrieved. Iterating through the names, if the query is not empty, it uses stristr() and substr() to look for a case-insensitive match at the beginning of each name. It constructs a string of hints and relays them to the client.

Example:

<?php
// Array with names
$a[] = "Android";
$a[] = "B programming language";
// ... other course names 
$q = $_REQUEST["q"]; // or $_GET["q"] 
$hint = ""; // 
if ($q !== "") { // 
    $q = strtolower($q); // 
    $len = strlen($q); // 
    foreach($a as $name) { // 
        if (stristr($q, substr($name, 0, $len))) { // 
            if ($hint === "") { // 
                $hint = $name; // 
            } else {
                $hint .= ", " . $name; // 
            }
        }
    }
}
echo $hint === "" ? "Please enter a valid course name" : $hint; // 
?>

Example 2: AJAX Auto Complete Search

In this example, recommendations are retrieved from an XML file and shown as links.

HTML: Contains a div for the suggestions and an input field. The JavaScript method showResult is triggered by the onkeyup event.

<form>
    <h2>Enter Course Name</h2>
    <input type = "text" size = "30" onkeyup = "showResult(this.value)">
    <div id = "livesearch"></div>
    <a href = "http://www.tutorialspoint.com">More Details </a>
</form>

JavaScript: ShowHint and showResult are comparable functions. An XMLHttpRequest is created, the response is handled by adding a border and changing the livesearch div’s innerHTML, and then an asynchronous GET request is sent to livesearch.php with the input as a query parameter.

Example:

function showResult(str) { //
    if (str.length == 0) { //
        document.getElementById("livesearch").innerHTML = ""; //
        document.getElementById("livesearch").style.border = "0px"; //
        return;
    }
    // Compatibility check for XMLHttpRequest
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest(); //
    } else { // code for IE6, IE5
        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); // true for asynchronous
    xmlhttp.send(); //
}

PHP (livesearch.php): This program loads the autocomplete.xml XML file. The query ($_GET[“q”]) is obtained. Iterating over
elements in the XML, if the query is not empty, it determines whether the query string is present in the value of the element (case-insensitive). The title and URL from the XML are used to create HTML anchor tags (<a>) for matches, and they are concatenated into a $hint string with <br/> between them. The created HTML or a default message is then echoed.

XML (autocomplete.xml): The PHP script uses this file to store its data. Each of the
elements that make up this structure has a and a <url>.</p>

<pages> //
    <link> //
        <title>android</title> //
        <url>http://www.tutorialspoint.com/android/index.htm</url> //
    </link>
    <link> //
        <title>Java</title> //
        <url>http://www.tutorialspoint.com/java/index.htm</url> //
    </link>
    <!-- ... other link elements ... -->
</pages>