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. This allows you to fetch options from the server when the user clicks on the select element or searches for a value in the search box.

In this tutorial, I show how you load MySQL database data remotely in Select2 with AJAX.

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 in the example. It has following structure –

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
);

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 single dropdown element. This is use to initialize select2 using jQuery.

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. Using this file handle select2 AJAX requests.

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

NOTE – Remove LIMIT if you want to fetch all records or update its value.

Create $data 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 data will not get loaded in the select2 element.

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 typed search value 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

Loading data in Select2 with AJAX is a powerful feature that allows you to create a more dynamic and data-driven search box.

In this example, I only passed the search value as data but you can also pass additional parameters with data that you require on the AJAX end.

If data is not loading in select2 then check your SQL queries again and try to debug it using the browser console and network tab.

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.