Implementation Of Ajax (Search Suggestion)

GOAL

Today’s goal is to implement a search suggestion as below. The suggestion should be displayed without page transition while inputting the search word.

Environment

Windows10
XAMPP 7.4.10

What is Ajax

AJAX, Asynchronous JavaScript And XML, is a term that refers to a group of Web development techniques for asynchronous communication on the client side using JavaScript. Please check “What Is AJAX (and Asynchronous Communication)?” for details about ajax.

The following is a brief explanation about the ajax mechanism.

How Ajax works

In Ajax, the 2 system “sending the request and getting the response from the server” and “get the data from the browser and reflect the received data to the browser” are separated. So users can operate on the browser while waiting the response.

This image has an empty alt attribute; its file name is image-2.png

The system which manage exchange of the data between server and client is called “Ajax engine”.

Method of implementation

Ajax dataflow

XMLHttpRequest() object sends a HTTP request, catches the response and gets the received value.

1. Receive a data update request from the browser UI.

This image has an empty alt attribute; its file name is image-7.png

2. Create XMLHttpRequest() in JavasScript and define the function to call when the communication is completed.

This image has an empty alt attribute; its file name is image-8.png

3. Send a request with XMLHttpRequest()

This image has an empty alt attribute; its file name is image-16.png

4. Receive XML, Json or some data as a response.

This image has an empty alt attribute; its file name is image-17.png

5. Reflect the received data on the browser.

This image has an empty alt attribute; its file name is image-15.png

Implementation of Ajax

First I created a database in the same way as “How to Create Database of MariaDB in XAMPP“. Assume there is a big database, though it is easier to get all data at first then get data every time because the sample database is too small.

database name: profile
table name: user column(id, name, age, icon)

This image has an empty alt attribute; its file name is image-12.png

1. Create a search form

Create a search form with <form><input></input></form> in index.php.

This image has an empty alt attribute; its file name is image-13.png

index.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
</head>
<body>
    <form action="">
        <label>Name:</label>
        <input id="input-area" type="text" name="word" list="name-list" autocomplete="off" /><input type="submit" value="Search" />
        <datalist id="name-list">
        </datalist>
    </form>
</body>
</html>

In this article, I implemented only suggestion part for sake of simplicity. In actual use, some method such as “POST” or “GET” are requested to the server when submit button pressed and the result will be displayed with a page transition.

Suggestions will be displayed by inserting items into <datalist></datalist> tag.

2. Create XMLHttpRequest() object in JavaScript and send the request

In index.php

<script>
    var input_area = document.getElementById('input-area')
    input_area.addEventListener("input", search);

    function search(){
        var ajax =  new XMLHttpRequest();

        var word = input_area.value;
        ajax.open('GET', 'search.php?q='+ word);

        ajax.onreadystatechange = function(){
            if(ajax.readyState == 4){
                var suggest = document.getElementById("name-list");
                var result_json_str = ajax.responseText;
                var name_list_tags = "";
                if(result_json_str != ""){
                    var result_json_obj = JSON.parse(result_json_str);
                    for(k in result_json_obj){ // get keys
                        var item = result_json_obj[k];
                        name_list_tags += '<option value="' + item['name'] + '">';
                    }
                }
                suggest.innerHTML = name_list_tags;
            }
        }
        ajax.send();
    }
</script>

The followings are details of the source code above.

When the input of the search form changes, the function search() is called.

<script>
    var input_area = document.getElementById('input-area')
    input_area.addEventListener("input", search);

In function search(), create XMLHttpRequest object.

var ajax =  new XMLHttpRequest();

Then create a request with XMLHttpRequest.open(). The argument async determine the communication is synchronous or asynchronous. Default value is true (asynchronous communication).

In this example, I used request method GET and the URL to send the request to is “search.php” that is mentioned below. The input word is passed as the name “q” with ?q=+ word.

var word = input_area.value;
ajax.open('GET', 'search.php?q='+ word);

Use XMLHttpRequest.onreadystatechange and register a callback function to be executed when there is a change in communication status.

Functions can be called according the state with XMLHttpRequest.readyState.

readyStatの値state
0UNSENT
1OPENED
2HEADERS_RECEIVED
3LOADING
4DONE

In this example, when the communication is complete, the system gets the name list from XMLHttpRequest.responseText as a Json format and inserts them into <datalist></datalist>. If you’d like to know about Json data exchange in PHP and JavaScript, please check “How To Create JSON Data In PHP”.

ajax.onreadystatechange = function(){
    if(ajax.readyState == 4){
        var suggest = document.getElementById("name-list");
        var result_json_str = ajax.responseText;
        var name_list_tags = "";
        if(result_json_str != ""){
            var result_json_obj = JSON.parse(result_json_str);
            for(k in result_json_obj){ // get keys
                var item = result_json_obj[k];
                name_list_tags += '<option value="' + item['name'] + '">';
            }
             
        suggest.innerHTML = name_list_tags;
    }
}

The request can be send with XMLHttpRequest.send().

ajax.send();

3. Communicate with the database in PHP

Receive the search word and communicate with the database in search.php,.

search.php

<?php

$dsn = 'mysql:host=localhost;dbname=profile';
$username = 'root';
$password = '*******';

if ($_GET) {
    try {
        $query=$_GET["q"];
        $dbh = new PDO($dsn, $username, $password);
        if($query==""){
            echo "";
        }
        else{
            $sql ="select * from user where name like '".$query."%'";
            $sth = $dbh->prepare($sql);
            $sth->execute();
            $result = $sth->fetchAll();
            $names = [];
            if($result){
                foreach ($result as $row) {
                    $names += array($row['id'] => array("name" => $row['name'], "age" => $row['age'], "icon" => $row['icon']));
                }
                echo json_encode($names);
            }
            else{
                echo "";
            }
        }
    }catch (PDOException $e) {
        echo  "";
        exit();
    }
}
?>

The followings are details of the source code above.

Use PDO to access the database in PHP. (Details: Access MySQL with PHP in XAMPP)

$dsn = 'mysql:host=localhost;dbname=profile';
$username = 'root';
$password = '*******';

if ($_GET) {
    try {
        $query=$_GET["q"];
        $dbh = new PDO($dsn, $username, $password);

Use the SQL SELECT statement WHERE LIKE operation to get the data that starts with the search word. (Related article: Create Search Form with PHP)

$sql ="select * from user where name like '".$query."%'";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();

Access each item in selected data by the for loop and generates the Json format data. You can pass the data as XMLHttpRequest.responseText in JavaScript by outputting with echo. (Related article: How To Create JSON Data In PHP)

$names = [];
if($result){
    foreach ($result as $row) {
        $names += array($row['id'] => array("name" => $row['name'], "age" => $row['age'], "icon" => $row['icon']));
    }
    echo json_encode($names);
}

Complete source code

The complete source code is in https://gist.github.com/s-nako/dfd7bb90bcbd64f7a34b76ae339ab26b.

Result

The suggestions are displayed while user inputting the word.

This image has an empty alt attribute; its file name is image-14.png

Supplement

In search like this, the data once acquired can be reused. (For example, if you just type j and get [‘Jack Road’,’John Mark’,’John Perrill’], then the names start with ja, jb, jc … can be searched from there).

If you need to get data again every time, such as when displaying the top of the search results, this method will works well.