Create your custom autosuggestion plugin powered by JQuery & Ajax

Rating: 3.0. From 1 vote.
Please wait...

Hey mates,

Last time we shared how you can use Typeahead.js for creating Searchable and autosuggest input box. If you don’t want to use any external plugin then this tutorial will serve as a handy tool for you to Create an Auto suggested and Searchable input box Powered by AJAX & jQuery.

For large datasets, some plugins fail and some take too much time to load the data, but with your own script, these issues are resolved as you have full control over the behavior of your own custom plugin or we can say script.

So let us begin the tutorial.

Firstly, we will create a sample page having input type in it on whom you want suggested data to load.

Filename: index.php

1
2
3
4
5
6
7
<h2 style="text-align:center">Create Your Own Autosuggested Functionality Powered by AJAX - PHP Hurdles</h2>
<div style="color:red;text-align:center">Type any Country Name</div>
<div style="text-align:center" class="hurdles">
<input type="text" name="query" value=""><br/>
<div class="result"></div><br/>

</div>

After creating the search box now will establish the database connection. Create a file database.php and include it in index.php

1
2
3
4
<?php
/* PHP Hurdles */
$link = mysqli_connect('localhost','root','','phphurdles_autosuggest')or die("error with database connection");
?>

 

Now we will fire a jquery code which will show results as the user enters 2 characters it will display the suggested country name based on user input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('.hurdles input[type="text"]').on("keyup input", function(){
        /* Get input value on change */
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length>1){
            $.get("ajax.php", {term: inputVal}).done(function(data){
                // Display the returned data in browser
                resultDropdown.html(data);
            });
        } else{
            resultDropdown.empty();
        }
    });
   
    // Set search input value on click of result item
    $(document).on("click", ".result p", function(){
        $(this).parents(".hurdles").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});
</script>

Now the last step is to create a query which will fetch the results from our database table for this we will  create a page ajax.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
include('database.php');

if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 

$term = mysqli_real_escape_string($link, $_REQUEST['term']);
 
if(isset($term)){
   
    $sql = "SELECT * FROM country WHERE country LIKE '%". $term . "%'";
    //echo $sql; exit;
    if($result = mysqli_query($link, $sql)){
        if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){
                echo "<p>" . $row['country'] . "</p>";
            }
            // Close result
            mysqli_free_result($result);
        } else{
            echo "<p>No matches found</p>";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}
 
// close connection
mysqli_close($link);
?>

So, ajax.php will enable you to get the list of all the country as the suggestion based on your input just click and select the country you want to enter into your search box.

Hope this tutorial will be beneficial for most of our newbie developers and will make the concept of Ajax clear to them.

You can download the customized working tutorial especially made for you people by clicking the Download link.

You can also visit our other trending topics:

Sending JSON Post Request To Server In PHP

Animated Ajax Record Deletion Using jQuery PHP

Hope our above tutorials will help you in facing the Development Hurdles.

Because we believe Hurdles aren’t really Hurdles.

3 Comments

  1. Yves said:

    This works great, but is it also possible to put ajax.php in a subfolder and call it? Because for me it only works when I put both files in same directory.

    No votes yet.
    Please wait...
    July 13, 2017
    Reply
    • Saurabh Dubey said:

      Yes we can put the ajax file in any folder inside the project provided we should you use absolute path for it.

      No votes yet.
      Please wait...
      July 14, 2017
      Reply
  2. ig said:

    I think the admin of this site is in fact working
    hard in support of his web site, since here every stuff is quality based stuff.

    No votes yet.
    Please wait...
    August 3, 2017
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
27 − 26 =