Select 2 basic remote data set integration

Select 2 is a jQuery plugin for select boxes. Using Select 2 we can search in a select box’s option values and connect with remote data set in json format.

Here we look how to inegrate select 2 with a remote data set( or simply from a json response url from our own web application).

The format of json response need to be like this (View http://www.appunitz.com/json/usa.php)


{
"results": [{
"text": "New York",
"id": "1"
}, {
"text": "California",
"id": "2"
}, {
"text": "Los Angels",
"id": "3"
}],
"more": false
}

The key value of ‘text’ will be shown in option text and key value of ‘id’ will be shown in option id.

View the fiddle to look how this works.

Including Select 2


<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css">

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>

HTML

<select></select>

CSS


.select2-container{
width:200px !important;
}

JAVASCRIPT



$('select').select2({
    placeholder: "Search",
    minimumInputLength: 1,
    ajax: {
        url: "http://www.appunitz.com/json/usa.php",
        dataType: 'json',
        data: function(term, page) {
            return {
                q: term,
                page_limit: 10,
            };
        }
    }
});

PHP



<?php
$usa_states = array( 
               array('text'=>'Texas','id'=>1), 
               array('text'=>'New Jersey','id'=>2), 
               array('text'=>'New York','id'=>3), 
               array('text'=>'Washington','id'=>4), 
               array('text'=>'California','id'=>5), 
               array('text'=>'Los Angels','id'=>6), 
               array('text'=>'Florida','id'=>7), 
               array('text'=>'Alaska','id'=>8), 
               array('text'=>'Massachusetts','id'=>9), 
               array('text'=>'Arizona','id'=>10) 
              );
$array['results'] = $usa_states;
$array['more'] = false;
header("Content-type:application/json; charset=utf-8");
echo json_encode($array);

Leave a Reply

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