Autocomplete Search With Ajax in PHP and MySQL Example
In this post, we will learn Autocomplete Search With Ajax in PHP and MySQL Example. i explained simply step by step how to PHP MySQL Ajax Live Search Autocomplete Example . Here you will learn PHP — Ajax Auto Complete Search. This tutorial will give you simple example of jQuery Autocomplete Search using PHP,MySQL and Ajax.
I will give you simple Example of How to PHP MySQL Ajax Live Search Autocomplete.
Are you showing the right products, to the right shoppers, at the right time? Contact us to know more.
In this article, we will see how to create an autocomplete search in PHP. Autocomplete feature is used to provide the auto suggestion for users while entering input. In this tutorial, we are going to suggest country names for the users based on the keyword they entered into the input field by using jQuery AJAX.
jQuery Autocomplete function is called on the key-up event of the input field. This function requests PHP for the list of countries via AJAX by sending the value of the input field. In PHP, it reads country names from the database that starts with the keyword entered by the user.
Autocomplete search in PHP
In the following code, the HTML has a search input and a suggestion box to display AJAX autocomplete results. On the key-up event of the search input field, it calls jQuery function to auto-suggest countries to the user.
The following jQuery script uses AJAX to send user input to a PHP page to fetch auto-complete suggestion. On success, the list of countries will be shown to the user. On clicking the list of suggested item, then the value is added to the input box.
// AJAX call for autocomplete$(document).ready(function() $("#search-box").keyup(function() $.ajax( type:"POST",url:"readCountry.php",data:'keyword='+$(this).val(),beforeSend:function() $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");>,success:function(data) $("#suggesstion-box").show();$("#suggesstion-box").html(data);$("#search-box").css("background","#FFF");>>);>);>);//To select country namefunctionselectCountry(val)$("#search-box").val(val);$("#suggesstion-box").hide();>
Reading Country Names from Database using PHP
In PHP code, it fetches data from the country table where the country name starts with the keyword passed by the AJAX request. After getting the results from the database, it iterates the resultant array and forms auto-complete suggestion list.
php require_once("dbcontroller.php");$db_handle=newDBController();if(!empty($_POST["keyword"]))$query="SELECT * FROM country WHERE country_name like '".$_POST["keyword"]."%' ORDER BY country_name LIMIT 0,6";$result=$db_handle->runQuery($query);if(!empty($result))?>id="country-list">phpforeach($resultas$country)?>php echo $country["country_name"];?>');">php echo $country["country_name"];?>php>?>php>>?>
Welcome dear readers, this article is going to focus on explaining autocomplete search box in PHP and MySQL. I know almost everyone uses Google to search the web. You may have noticed suggestions appearing when you start typing any keyword in Google’s search box. It is actually an autocomplete search box. This functionality makes it easy for users to search your content and increases user engagement. Let’s learn how to build such an autocomplete search box using jquery ajax and PHP.
How to build autocomplete search box in PHP MySQL and ajax?
I am dividing the complete concept into different steps to make this guide easily understandable.
Create a search box form with a submit button.
Write a key-up event and fetch suggestions.
Create a list click event to load suggestions into the search box.
Fetch the search results by creating a submit button click event.
Now it’s time to perform all the above-mentioned steps practically one by one. Don’t worry! I will share the code also at the end of the article.
How to create a auto complete search box form using bootstrap?
It’s basically an input text field where users will write their search queries. I am going to use bootstrap to create this search box.
Create an input text field inside the HTML form tag and set its id to “search”.
Set the autocomplete attribute to “off” to disable the browser autosuggestions.
Also, create a submit button and use a search icon instead of text to beautify the search box.
Set the id attribute of the submit button to “submit”. We will use these id’s in the jquery ajax part later in this article.
Besides the search box, we need two more divisions with id’s “list” and “card”. The list div will be used to show a suggestion list and the card will be the place to display search results.
How to fetch Auto complete search box suggestions using ajax and PHP?
This step is the core part of this article. In this part, we are actually going to create a key-up event. whenever a user presses a key, suggestions will be fetched using an ajax request and PHP script.
First, create a key-up event on the search box when the document is ready using jquery.
Store the data of the search box in the “search_query” variable and then write an ajax call if the search query is not empty.
If the search_query is empty, fade out the list div. It is because when the user erases his search query, the suggestion list will automatically disappear.
In the success part of the ajax call, display the returned list of suggestions in the “list” div using html() function.
That’s all about jquery and ajax call. Now see how to search and fetch suggestions in the database using PHP.
Since we are fetching data from the database, we obviously need a database connection.
Now write an SQL select query to fetch only unique records from the database using a distinct clause.
Use like operator instead of equal to in the where clause to fetch record based on maximum similarity.
Execute the query and fetch the data from the database.
Arrange the data in the form of a list inside a $html variable using concatenation.
Now see how this code will work. First, when the user enters anything in the search box, the search query will be sent to the PHP page using ajax call. Unique suggestions will be fetched on the PHP page and sent back to ajax in a bootstrap list format. In the ajax success part, the received list will be displayed to users in the “list” div.
How to load the suggested keywords in the auto complete search box?
As the user enters anything, suggestions will be displayed to him. Now the user must be able to load any suggestion in the search box on click. In this part, we will add a click event of list li. So when the user clicks on any list item, its text will be loaded in the search box.
Create a click event on li of the unordered list.
Set the value of the search box to the text inside the list item.
Also, fade out the suggestion list using the fadeout() function.
Now when the user clicks on any suggestion, the list item text will be loaded in the search box and the suggestion list will disappear.
How to submit search queries and fetch search results?
This is the final and interesting part of the article. When the user clicks the submit button, the search query will be sent to a PHP page through an ajax post request. Data related to the search query will be fetched but this time arrange inside bootstrap card format. finally, the success part of the ajax request will display the records in the “card” div.
Create a click event on the submit button and then fetch the query from the search box in a search_query variable.
Send the variable to the PHP page through an ajax request.
Upon the success of the ajax call, display the search results received in the “card” div.
That’s the details of the ajax call. Now let’s see how the PHP script will fetch data.
Now inside the PHP script, execute an SQL select query with like operator instead of equal in the where clause.
Retrieve the records in a bootstrap card format inside the $html variable.
Echo the $Html variable to send the search results back to ajax.
real_escape_string($_POST['search']); $query = "SELECT * FROM books WHERE title like '%%'; "; $result = $conn->query($query) or die($conn->error); $html = ""; if (mysqli_num_rows($result) > 0) < while ($row = mysqli_fetch_assoc($result)) < $html .= ''; $html .= '
' . $row['title'] . '
'; $html .= '
' . $row['author'] . '
'; $html .= '
' . $row['description'] . '
'; $html . ; > > else < $html .= "Sorry! No record found"; >echo $html; > $conn->close();
That’s it we have completed all the steps to build autocomplete search box in PHP MySQL.
Output of the code:
We have completed our ajax autocomplete search in PHP successfully. I tried to explain everything related to autocomplete stepwise. You can enhance the functionality of this example further using your creativity. I hope you liked this information. Thanks for reading and supporting us.