Tuesday, December 25, 2018

Select2 Jquery Plugin Using Remote Data Loaded Using Ajax PHP and PDO

Select2 plugin is : Its a Jquery plugin to turn an input/select field into a dropdown select box with searchable and stylable features such as adding the image with options, navigate to option with arrow keys, etc.

Head over to https://select2.github.io/ to find out more.

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.

So continuing their excellent plugin they have now improved and upgraded the plugin to Version 4.

And although the documentation has improved, it still is quite hard to understand the concept of Ajax remote data pulled from a MySQL database into the plugin.

For this tutorial you will need the CSS files and JS files located within the dist folder.

Within your head area make sure you include the location to the .css file.

And within the footer ensure you have loaded jquery and then the select 2 plugin.

So thats the basics loaded into the page.

Table 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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Configuration

db.php file
<?php
/*
database values for the application.
*/
$db_server = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "tutorial";
/*
connecting to the database using PHP PDO. all the database connectivity in the application is handled using PDO only for injection proof queries.
*/
try {
 $db = new PDO("mysql:host={$db_server};dbname={$db_name};charset=utf8", $db_user, $db_password);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
 /* displaying the error page over here. */
 echo "Database connection failed";
}
?>

Include jQuery Select2 Files

index.html
<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>

HTML File

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

PHP Get Data File

dataFetch.php file.
<?Php
include "db.php";

try
{
 if(!isset($_POST['searchTerm'])){ 
  $sql = "SELECT `id_kel` AS id , `name` AS text FROM `users` ORDER BY `name` LIMIT 5";
 } else {
  $search = $_POST['searchTerm']; 
  $sql = "SELECT `id_kel` AS id , `name` AS text FROM `users` WHERE `name` LIKE CONCAT('%', :search, '%') ORDER BY `name` LIMIT 5";
 }
 $sql_do = $db->prepare($sql);
 $sql_do->bindParam(':search', $search, PDO::PARAM_STR);
 $sql_do->execute();
 $num = $sql_do->rowCount();
} catch(PDOException $e) { 
 $log->logError($e." - ".basename(__FILE__));
}
if ($num>0)
{
 foreach($sql_do as $row)
 {
  $data[] = array("id"   => $row['id'],"text" => $row['text']);
 }
}else{
 $data[] = array("id"   => "","text" => "tida ada data");
}
echo json_encode($data);
 
?>


jQuery Code

$(document).ready(function(){

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

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

View the official documentation for more details.

If you found this tutorial is so hard to understand feel free to commment.

0 Comments

Post a Comment