Tuesday, April 9, 2013

Integrate Remote Data using select2

I was trying to integrate the Select2 plugin for remote data. Select2 comes with AJAX/JSONP support built in. I am using this plugin for the first time. I followed the reference code from the following link  to write my code.

http://ivaynberg.github.io/select2/#ajax

HTML input should be a hidden input if you want to use a ajax function.

JavasSript code are as follows

$(document).ready(function () {



function format_city(obj){
            return obj.City;
}

$("#select_city").select2({
            minimumInputLength: 2,
            placeholder: 'Type in City Names...',
            multiple:true,
            ajax: { 
                url: base_url+"property/getCities",
                dataType: 'json',
                data: function (term) {
                    return {
                        q: term, // search term
                        page_limit: 10
                    };
                },
                results: function (data) { 
                    return {results: data, text:'City'};
                    
                }
            },
            formatResult: format_city, 
            formatSelection: format_city
            
        });
});

My Ajax function return json value. which contains data like  [{City:'Anderson',City:'New York'}]


ajax: { 
    url: base_url+"property/getCities",
    dataType: 'json',
    data: function (term) {
          return {
             q: term, // search term
             page_limit: 10
           };
        },
        results: function (data) { 
        return {results: data, text:'City'};
    }}


When I run the script it was not working properly. I spend almost 1 hours and after that come to know the big issue. Actually result of json data requires a "id". if in the result its not found that it will not work.

I have added the following code


$("#select_city").select2({
.....
id: function(obj) {
    return obj.City; // use slug field for id
},
.....
});

1 comment:

  1. The Most Interesting Slot Machines You Can Play In 2020 - drmcd
    Looking for a 제주도 출장안마 way to play the most interesting slot machines 당진 출장마사지 you can play? We have 익산 출장샵 an extensive list of the 성남 출장안마 most popular slots available on the 익산 출장안마 market.

    ReplyDelete