Jquery Select2 v4 Ajax/PHP Tutorial

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.

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:

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.

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.

Leave a Response

15 Responses

  • Davide3i
  • June 14th, 2015

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?

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.

  • Davide3i
  • June 14th, 2015

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. 🙂

  • Anand
  • July 13th, 2015

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.

  • Kamoris
  • July 17th, 2015

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!

Thank you very much for this tutorial, although I am good at PHP, I suck on JS and this helped me alot.

Wish you all the best!

  • Moe
  • January 30th, 2016

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 Pajaron
  • February 15th, 2016

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

doesn’t seem to help.

  • Martin
  • June 7th, 2016

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…

Thank you very much for this tutorial, this helped me alot.

very useful thanks!

Perfect tutorial. Thank you. Its too simple.

This is awsome. made my day. thaks

Thankful ! great tutorial 🙂

  • adriano
  • August 16th, 2017

thx great tutorial it is time to update with result data formatting.