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.
Hi, I want to make a dual search, where I can search the names by id and names also. How can I do it in the query?
LikeLike
sure.. you can do it. just change the query to this “select name from names where name like ? or id like ?”.
for the other parameter you can set $keyword2=”%$keyword2%” i.e the id.
If you want id and names to appear seperately.
LikeLike
where to put it?
LikeLike
about what?
LikeLike
Hi, how could I make the search results clickable, so the clicked results appear in the input field then?
LikeLike
all you need to do is just add element in the fetched results.
eg.
Fetched Item
LikeLike
all you need to do is just add
element in the fetched results.
eg.
LikeLike
I’m having another problem now, I described it here:http://stackoverflow.com/questions/40509104/laravel-ajax-live-search-not-working-properly .. Can you answer it right on stackoverflow or here?
LikeLike
well i checked the your js script which is fine …. are you facing problem with php script ?
LikeLike
You can try my php script to fetch the results.
LikeLike
Hi, I have a problem here…
what’s …’s’ here….$statement->bind_param(‘s’,$keyword);
it give me an error!!!
once again
echo “$name”;
but where is $name ???
anyway I like the code because it’s really simple 😉
LikeLike
‘s’ represents type of data, here it is string.
in the next step we first bind the results to variables and then fetch it.
so here we bind the name in the database to $name variable.
LikeLike
thanks for the instant search…!!!
i need a search button too.. that i did, but when ever i clicked it, the page gets reloaded and the results are gone… can you help me with this..???
LikeLike
Sure.. you just need to attach an event handler “submit” to the form id and preventDefault() to prevent default handling of the form.
$(“form-id”).on(“submit”,function(ev){
ev.preventDefault(); // that will prevent the reloading of the page.
// here goes your ajax call.
})
LikeLike
hi bro.. is it save ? what i mean by save is can i use it in the big projects how fast is it ? thx
LikeLike
Well.. i have used prepared statements which is quite safe than normal queries but it is still XSS vulnerable…tho u need to properly check the input of the user and some security measures like escaping characters.
answer remains ambiguous.
LikeLike
Hi,I got this ajax live search working in wordpress site.I used this anspress plugin search box.Can you explain in detail by posting code on how can i add arrow navigation in this code.I want users to be able to navigate search result list using their arrow keys.More details here,i also posted in Stackoverflow. (http://stackoverflow.com/q/43434748/7744586).
LikeLike