In this tutorial i will show you how you can make your own live search with Ajax which is similar as Google Autocomplete.

Live search has many benefits compared to traditional searching:

  • Results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result

So for this we have our database table which contains some name and we will search from it. Well you can have any content to search from like products,students name etc. anything you like.

So how this works? .. well we will use (select * from something where something like %key%) in our sql query. We use Ajax to send this keyword to our php script to fetch the data from our table every time the user presses the key ( ‘keyup ‘ event handler ).

So this is my table structure

names

create table names (
  id INT (6) unsigned auto_increment PRIMARY KEY,
  name varchar(200) not null
);

well there is only name field but you can have more field to search from. Now this is my Index.php page.

<div id="main">
    <div id="header"><h1>Find Names</h1></div>
    <div id="content">
        <input type="search" name="keyword" placeholder="Search Names" id="searchbox">
        <div id="results"></div>
    </div>
</div>

style.css

#main {
    position: absolute;
    width: 70%;
    left:15%;
    top:0;
    height:100%;
    background: #e3dfd7;
    overflow-y: hidden;
}
#header { padding: 20px;}
#header h1 {
    color:#222222;
}
#content {
    height: inherit;
    background: #ebebeb;
    width: 100%;
    padding:20px;
    box-sizing: border-box;
}
#content input {
    width: 100%;
    font-size:20px;
    color: #424242;
    padding:10px;
}
#results{
    width:100%;
    display: none;
    bordder-bottom:1px solid black;
    bordder-left:1px solid black;
    bordder-right:1px solid black;
}
#results #item {
    box-sizing: border-box;
    padding:10px;
    font-size:18px;
    width: 100%;
    background: white;
    border-bottom:1px solid #bdbdbd;
}

So here is the fetch.php which fetches the data from our table from a keyword.

<?php
    if($_GET['keyword'] && !empty($_GET['keyword']))
    {
        $conn = mysqli_connect('localhost','root','','work'); //Connection to my database
        $keyword = $_GET['keyword'];
        $keyword="%$keyword%";
        $query = "select name from names where name like ?";
        $statement = $conn->prepare($query);
        $statement->bind_param('s',$keyword);
        $statement->execute();
        $statement->store_result();
        if($statement->num_rows() == 0) // so if we have 0 records acc. to keyword display no records found
        {
            echo '<div id="item">Ah snap...! No results found :/</div>';
            $statement->close();
            $conn->close();

        }
        else {
            $statement->bind_result($name);
            while ($statement->fetch()) //outputs the records
            {
                echo "<div id='item'>$name</div>";
            };
            $statement->close();
            $conn->close();
        };
    };
?>

Now we are ready with with our php scripts. But without Ajax it is tasteless, so here is the Ajax Script part.

<script src="jquery.js"></script>
<script>
    $(document).ready(function () {
        $("#searchbox").on('keyup',function () {
            var key = $(this).val();

            $.ajax({
                url:'fetch.php',
                type:'GET',
                data:'keyword='+key,
                beforeSend:function () {
                    $("#results").slideUp('fast');
                },
                success:function (data) {
                    $("#results").html(data);
                    $("#results").slideDown('fast');
                }
            });
        });
    });
</script>

In this jquery.js is my downloaded jquery script. You can download it from here or you can use the Jquery CDN. Here i have attached a ‘keyup’ event handler

$("#searchbox").on('keyup',function(){});

So whenever a user presses a key it sends the typed keyword to our fetch.php script, then it fetches the records from table and sends back to the index.php page and then we output the data into $(“#results”).

And that’s all.

You Can Download a Sample Project Here.