Loading data remotely in Select2 with AJAX

Select2 is a jQuery plugin that extends the functionality of a simple HTML drop-down element by allowing to search the list, add the image with options, navigate to the option with arrow keys, etc.

It comes with AJAX support which you can call it in the same way as $.ajax in jQuery.

The plugin provides the currently inputted value in the search box which can be used as data in the AJAX request.

Loading data remotely in Select2 with AJAX


Contents

  1. Table structure
  2. Database Configuration
  3. Download and Include
  4. HTML
  5. PHP – Return select2 data
  6. jQuery – Initialize select2
  7. Demo
  8. Conclusion

1. Table structure

I am using users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database Configuration

Create a config.php for database configuration.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download and Include

  • Download the library from here.
  • Include select2.min.css and select2.min.js files with the jQuery library in the <head> section. You can also use the CDN.
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

4. HTML

Create a drop-down element.

Completed Code

<select id='selUser' style='width: 200px;'>
 <option value='0'>- Search user -</option>
</select>

5. PHP – Return select2 data

Create a getData.php file.

Select 5 records from the users table if $_POST['searchTerm'] is not set otherwise select 5 records where $search matches in the name field.

Create an array that initializes with user id and name. Return the array in JSON format.

NOTE – While creating associative array for initialize the Array make sure that their you have defined id and text keys otherwise the HTML element will not be initialized.

Completed Code

<?php
include 'config.php';

if(!isset($_POST['searchTerm'])){ 
    $fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{ 
    $search = $_POST['searchTerm'];   
    $fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
} 

$data = array();
while ($row = mysqli_fetch_array($fetchData)) {    
    $data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);

6. jQuery – Initialize select2

Call select2() method on the <select id='selUser'> to initialize the plugin. To load records remotely specify ajax option where set its url, type, dataType, delay, data, and processResults.

Get the entered values using params.term in data. The successful callback handle by processResults function where initialize results with the response.

Completed Code

$(document).ready(function(){

 $("#selUser").select2({
     ajax: { 
         url: "getData.php",
         type: "post",
         dataType: 'json',
         delay: 250,
         data: function (params) {
             return {
                 searchTerm: params.term // search term
             };
         },
         processResults: function (response) {
             return {
                 results: response
             };
         },
         cache: true
     }
 });
});

7. Demo

View Demo


8. Conclusion

Define the ajax option in select2() method while initializing the element. Initialize results with the return response.

View the official documentation for more details.

You can view this tutorial to know how to load data using PDO in select2.

If you found this tutorial helpful then don't forget to share.