Jquery Select2 v4 Ajax/PHP Tutorial | South Coast Web Design Ltd
South Coast Web Design Ltd
Jquery Select2 v4 Ajax/PHP Tutorial Jun 14

Jquery logoSince my last tutorial on the Select2 Jquery  plugin using remote data loaded using Ajax and PHP has been so successful, I am updating the tutorial to work with the newer Version 4 plugin.

If you dont know what the Select2 plugin is : Its a Jquery plugin to turn an input/select field into a dropdown select box with searchable and stylable features.

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

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.

As my last tutorial on V3 of the plugin has been so helpful to many people and I have been asked about Version 4 I am going to show you how to use the plugin with a small PHP script to pull remote data from the database.

If you would prefer to use the Version 3 of this plugin you can view my tutorial here : jquery-select2-ajax-tutorial

Firstly if you have’nt already downloaded the plugin go on over to their site or onto Github and grab a copy of 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.


<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/select2.min.js"></script>

So thats the basics loaded into the page.

Now for the HTML.
** The old version used to convert a hidden Input field into a select2 dropdown. **

So you add a Select box to your HTML form:


<!-- Product Name Select Box -->
<div class="form-group">
   <label class="col-sm-4 control-label">Product Name</label>
   <div class="col-sm-6">
      <select class="productName form-control" name="productName"></select>
   </div>
</div>

 

And a little bit of Jquery


$( ".productName" ).select2({        
    ajax: {
        url: "/ajax/productsList.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term // search term
            };
        },
        processResults: function (data) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
            return {
                results: data
            };
        },
        cache: true
    },
    minimumInputLength: 2
});

So after the input length has reached 2 characters it uses ajax to load the results from our page set in the URL element.
It is going to send the Search String through to the php as $_GET in the field name of : q.
So our ajax request will go : /ajax/productsList.php?q=

Now some PHP
We will use a small php script to connect to a MySQL Database and search for a matching field.
I always use PDO with MySQL and prepared statements. This should prevent any chance of MySQL Injection which older MySQL queries did not protect against Out of the box
If you are unsure how to connect to a Database there are plenty of Tutorials on the web on how to do this.


<?php 
// connect to database 
require('includes/db.con.php');

// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial 
$search = strip_tags(trim($_GET['q'])); 

// Do Prepared Query 
$query = $smnt->prepare("SELECT productId,productName FROM products WHERE productName LIKE :search LIMIT 40");

// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));

// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);

// Make sure we have a result
if(count($list) > 0){
   foreach ($list as $key => $value) {
	$data[] = array('id' => $value['productId'], 'text' => $value['productName']);			 	
   } 
} else {
   $data[] = array('id' => '0', 'text' => 'No Products Found');
}

// return the result in json
echo json_encode($data);

?>

if you have firebug installed on firefox you should see something similar to this.

firebug for select2 results
and the results within the page will look like
Select2 Ajax results

If you view the remote data load on the Plugin page you see the results can be translated in many ways and styled in an image/list results.
Please read the documentation there to learn how to do this.

Hopefully this has helped you if you have upgraded from version 3 to version 4 of the Jquery Select2 plugin.

14 Responses to “Jquery Select2 v4 Ajax/PHP Tutorial”

Davide3iJune 14th, 2015 at 11:42 am

Nice tutorial, thanks.
I’ve a question, though: could you please make a similar tutorial for giving the chance to adding new tags/options to the database if a user types one that is not in it?

southcoastwebJune 14th, 2015 at 12:39 pm

Hi , i have come across a similar issue to this before and found the Select2 plugin is not correct to use for the instance.
I would use jquery ui autocomplete to do this myself.
If i get chance in the next few days i will get a tutorial added.

Davide3iJune 14th, 2015 at 1:48 pm

Ok!
I’d really appreciate a similar tutorial, ’cause I’m really struggling to create a similar function for an university’s project I’m working on.

Thanks. 🙂

AnandJuly 13th, 2015 at 7:09 am

Excellent tutorial, I am following this method to populate my select2. But Davide asked, I would like to have the functionality of adding new options to the dropdown if not present and add the newly created values to DB.

KamorisJuly 17th, 2015 at 12:31 pm

Thanks for this tutorial,
I was fighting with it for 3 hours trying to follow Select2 documentation, then I found your tutorial and has it done in 2 minutes.
One more time, thanks!

MoeJanuary 30th, 2016 at 9:39 am

I have copied and pasted the same code and it just wont work i have everything included dbconx…jquery …select2 libraries …please in need of help here.

Devlin PajaronFebruary 15th, 2016 at 12:56 pm

Can you update the code and make it have multiple tagging support? Adding the
tags: true,
tokenSeparators: [‘,’, ‘ ‘]

doesn’t seem to help.

MartinJune 7th, 2016 at 1:10 pm

The select2 documentation and online examples are a little bit difficult to follow but with your tutorial I was up and running very quickly. Many thanks…

Leave a Response


Top