Suggestion field using jQuery is very useful for a web application. In this post, you will learn how to perform Google-like search textbox in PHP. Using jQuery UI we can efficiently show relevant suggestion from the database under a textbox.
Let’s start the suggestion textbox tutorial. Here we will display a textbox for posted article list. Once the user enters key in a textbox, the auto-suggestion post list would be listed below a textbox. Those auto-suggestion posts would be fetched from the MySql database.
Include required JS & CSS:
Initially, we want to include a required jQuery library, jQuery UI library, and jQuery UI stylesheet.
1 2 |
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <!-- CSS Link --> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <!-- JS Link --> |
Add HTML Textbox with Autocomplete function:
Add the textbox with a unique id to assign suggestion list result and also add the suggestion list function with a particular textbox with autocomplete() function and relevant attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="form-group"> <lable>Suggestion Post textbox:</lable> <input class="form-control" type="text" id="suggestion_textbox" /> </div> <!-- Script for autocomplete funtion --> <script> $(document).ready(function(e){ $("#suggestion_textbox").autocomplete({ source:'post_details.php' }); }); </script> |
PHP Source Script
Create table with following details
1 2 3 4 5 6 7 |
CREATE TABLE `li_ajax_post_load` ( `post_id` int(11) NOT NULL, `post_title` varchar(250) NOT NULL, `post_desc` text NOT NULL, `status` int(11) NOT NULL, PRIMARY KEY (`post_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
MySQL Database connection details
1 2 3 4 5 6 7 8 9 10 |
<?php //db details $db_host = 'localhost'; $db_user = 'root'; $db_pass = ''; $db_name = 'li_demo'; //connect and select db $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name); ?> |
Here first we need to get the text box entered key value to filter from a database value. Using $_GET[‘term’] we can get the entered key value and stored into PHP variable. Then we will fetch the data from post list table and filter the post title by the search key value. Finally, we will return the filtered post title data in JSON format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php require_once('./include/mysqli_connect.php'); $postDetails = array(); $search_key = $_GET['term']; //get rows query $query = "SELECT * FROM li_ajax_post_load where post_title like '%$search_key%'"; $result = mysqli_query($con, $query); //number of rows $rowCount = mysqli_num_rows($result); if($rowCount > 0){ while($row = mysqli_fetch_assoc($result)){ $postDetails[] = ucfirst($row['post_title']); } } echo json_encode($postDetails); ?> |