Select2 Ajax Example PHP |
X

Congrats, You are Subscribed to Receive Updates.

Select2 Ajax Example PHP


Introduction

The select2 js is widely used to shortlist and filter the select options. When it goes more than 100 in select option. Its hard to navigate and find the right one.  For that we can go with select2 js  or selectpicker. That’s also handy when the list is less than 1000. Because if you load all the list in DOM. That will slow down the speed of it. So let’s go with Ajax and server side filtering. Let’s say Select2 ajax example PHP.

Let’s go with an example of it. Let’s make the needy files ready for it.

Necessary files

Let’s use the CDN files of select2 JS and CSS files. which will give better performance. And we need one index.php  and ajax.php files. Lets say the file struce like this.

  • index.php
  • ajax.php

JS and CSS files we will include it inside the index.php and will make one select options and apply the default select2.  Lets create an empty php file for index with basic html tags. lets add our needs here.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://www.kvcodes.com/theme/js/jquery.min.js" > </script> 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

The above scripts and style should be added to link the jquery and select2. Then,lets make the select option element.

<p> Static Example </p>
<select class="static form-control" style="width:500px" name="itemName">
<option value="0"> None </option>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
<option value="5"> Five </option>
<option value="6"> Six </option>
<option value="7"> Seven </option>
</select>

<br><br>
<p> Ajax PHP from array </p>
<select class="itemName form-control" style="width:500px" name="itemName"></select>

Lets make the select options to select2.

// Static dropd down
$(".static").select2();

//Ajax array example
$('.itemName').select2({
placeholder: 'Select an item',
theme: "material",
allowClear: true,
ajax: {
url: 'ajax.php?filter=yes',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});

PHP Ajax Example

Now, lets make the ajax.php with PHP functionalities with below code.

$array = array(
 array('id' => '1','iso' => 'AD','local_name' => 'Andorra'),
 array('id' => '2','iso' => 'AE','local_name' => 'United Arab Emirates'),
 array('id' => '3','iso' => 'AF','local_name' => 'Afghanistan'),... );

For demo I gave less lines. from my down and download you will get full list.

if(isset($_GET['filter']) && $_GET['filter'] == 'yes') {
  $filter = [];
  foreach($array as $single){
    if(strpos($single['local_name'], $_GET['q']) !== false)
      $filter[] = array('id' => $single['iso'], 'text' => $single['local_name']);
  }
  echo json_encode($filter);
} elseif(isset($_GET['filterDB']) && $_GET['filterDB'] == 'yes') {
   define (DB_USER, "root");
   define (DB_PASSWORD, "123");
   define (DB_DATABASE, "select2");
   define (DB_HOST, "localhost");
   $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

   $sql = "SELECT countries.id, countries.local_name FROM countries
         WHERE local_name LIKE '%".$_GET['q']."%' LIMIT 10";
   $result = $mysqli->query($sql);

   $json = [];
  while($row = $result->fetch_assoc()){
     $json[] = ['id'=>$row['id'], 'text'=>$row['title']];
  }
  echo json_encode($json);
} 

That’s it.  You can demo and download the exmples here. Also comment in next tab,if you have any queries or enhancement with my demo.

Demo

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar