PHP JQuery Chosen Populate Ajax Autocomplete Example Tutorial

May 06, 2024 | PHP jQuery MySql Bootstrap Javascript Ajax


Hello Dev,

Today, I'd like to demonstrate how to implement jQuery autocomplete using the Chosen library in PHP. This tutorial will illustrate a straightforward method for dynamically searching through data using PHP and jQuery Chosen plugin.

Chosen is a widely-used jQuery plugin that enhances select boxes with user-friendly features, including search capabilities and support for multi-select functionality. Its flexibility allows for easy customization to suit various needs.

To begin, let's create a "countries" table and populate it with some sample records. Then, we'll create two PHP files: one for displaying the form with the select box and another for handling the AJAX requests. This setup will result in a layout similar to the screenshot provided below.

Feel free to ask if you need any further clarification or assistance!

To create a jQuery AJAX autocomplete using the Chosen library in PHP, you can follow these steps. This example will guide you through creating a simple form with a select box that uses AJAX to dynamically search and populate options using PHP. This approach can be adapted for various frameworks like Laravel or CodeIgniter.

Read Also: Laravel 11 Authentication Using Jetstream With Livewire Example Tutorial Step 1: Create the Database and Table

First, create a database and a table named countries with columns id and name. Here's an example SQL query to create the table:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24;
Step 2: Create the HTML Form with Chosen

Create an index.php file for your form. Include the necessary libraries for Bootstrap, jQuery, Chosen, and jQuery UI. Then, create a form with a select box that will be enhanced with Chosen for the autocomplete functionality.

<!DOCTYPE html>
<html>
<head>
  <title>PHP - JQuery Chosen Populate Ajax Autocomplete Example Tutorial -- ItErrorSolution.come</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div class="container">
  <div class="panel panel-default">
    <div class="panel-heading">PHP - JQuery Chosen Populate Ajax Autocomplete Example Tutorial -- ItErrorSolution.come</div>
    <div class="panel-body">
      <form>
        <select class="form-control select-box">
          <option>Select Option</option>
        </select>
      </form>
    </div>
  </div>
</div>
<script type="text/javascript">
  $(".select-box").chosen();
  $('.chosen-search input').autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "ajaxpro.php?name="+request.term,
        dataType: "json",
        success: function(data) {
          $('.select-box').empty();
          response($.map(data, function(item) {
            $('.select-box').append('<option value="'+item.id+'">' + item.name + '</option>');
          }));
          $(".select-box").trigger("chosen:updated");
        }
      });
    }
  });
</script>
</body>
</html>
Read Also: Laravel 11 Create Database Seeder Command Example Tutorial Step 3: Create the AJAX Handler

Next, create a PHP file named ajaxpro.php to handle the AJAX request. This file will query the database for matching country names based on the user's input and return the results as JSON.

<?php
$hostName = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

$mysqli = new mysqli($hostName, $username, $password, $dbname);

$sql = "SELECT * FROM countries WHERE name LIKE '%".$_GET['name']."%'";
$result = $mysqli->query($sql);
$response = [];

while($row = mysqli_fetch_assoc($result)){
  $response[] = array("id"=>$row['id'], "name"=>$row['name']);
}

echo json_encode($response);
?>

This setup provides a basic implementation of jQuery AJAX autocomplete using the Chosen library in PHP. You can further customize the appearance and behavior of the select box according to your needs.

Output: PHP JQuery Chosen Populate Ajax Autocomplete Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Bootstrap
#Javascript
#Ajax
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"