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, adding the image with options, navigate to the option with arrow keys, etc.

It comes with the AJAX supports where you can call it in the same way as $.ajax in the 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. Configuration
  3. Download and Include
  4. HTML
  5. PHP
  6. jQuery
  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. 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.
<meta charset="UTF-8">
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/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

Create a getData.php file.

Select all records with the limit of 5 when $_POST['searchTerm'] is not set otherwise select record according to the search term.

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

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.

33 thoughts on “Loading data remotely in Select2 with AJAX”

  1. well done!
    it is amazing and it is the best select2 tutorial I ever seen before
    Sir,can I predefined the selected option?
    i am appreciated greatly your help

    Reply
  2. I solved it by the follow code
    it require id and full_name
    can I complete it by only id
    many thanks
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger(‘change’);

    Reply
  3. very good tutorial, i needed this functionality for a select2 dropdown in yii2, i have googled it and found so many irrelevant answers, this one is the best i have seen ever

    Reply
  4. Thanks for the aowesome lesson.

    But what do I need to modify if I wanted to make 3 or select2 inputs with ajax in the same page.

    I tried it with two, but the JS code looks not working any more?

    Reply
      • Hi Yogesh,

        When I applied this to my page with multiple select2 with different data, the code stopped working, I had to put PHP codes in separated files in order to run them.

        Do you have an idea to put them all in one PHP file?

        Kind Regards,
        Sameh

      • Hi Sameh,
        For this, you need pass extra parameter with AJAX data like – data: function (params) {return {request: 1,searchTerm: params.term // search term};},Then on your AJAX file handle request with request parameter. I updated the example link.

  5. i want to select partiqular value on some situation. how can i do this?
    means how to select perticular value

    Reply
  6. sir how I will show my user data as per it will only show the id of user then can u just give an idea so it will help me

    Reply
    • Hi Lakshya,
      Do you want to show only user id in option text? In this case pass user id in text e.g. $data[] = array(“id”=>$row[‘id’], “text”=>$row[‘id’]); in AJAX file.

      Reply
  7. hi sir i need to show the data in to database mysql with select2 filter multiple checkbox with diffrent fiter field like country industry and emp range and sort the respected data plz help me

    Reply
  8. Hi,
    THIS IS URGENT…
    This code is superb. Ajax call loading data on database query but not loading in the dropdown box in my case… Need help…
    My CODE:
    Part1:

    Student Id *

    – Search student –

    Part2:

    $(document).ready(function(){

    $(“#StudentId”).select2({
    ajax: {
    url: “ajax_call_to_fetch_student_id.php”,
    type: “post”,
    //dataType: ‘html’,
    delay: 250,
    data: function (params) {
    //alert(JSON.stringify(params));
    return {
    searchTerm: params.term // search term
    };
    },
    processResults: function (response) {
    alert(JSON.stringify(response)); //I can see here that records are coming
    return {
    results: response
    };
    },
    cache: true
    }
    });
    });

    Thanks in Advance…

    Reply
    • num_rows > 0){
      $response = array();
      $i = 0;
      while($row = $result->fetch_assoc()){
      $response[] = array(“id”=>$i++, “text”=>$row[‘Student_Id’]);
      }
      //print_r($response);
      }
      echo json_encode($response);
      ?>

      Reply
  9. i tried your code, and working like a charm to show and seach data, but on search proccess i had a problem, if i search data, i can not search name in some id, here is my data:
    id: 1, text: text1,
    id:2, text: text2,
    id: 3, text: text3,
    id: 4, text: text4

    if i search text1 or text3, data show text1 or text3, but if i search text2 or text4 it not show text2 or text4, i dont know what i mistake. i just copy and paste your code, with my database. can you help me

    Reply
  10. Hello,

    I am getting issue in select2 ajax,
    when i select from searched list of ajax another ajax request executed and due to that i my select 2 dropdown not close.

    Reply

Leave a Comment