0

Hello I want to load country state and city using select2.js how can i achieve this? i make ajax call to load details of country state and city... i am facing problem when trying to make ajax call to load data using webmethod. BindCountryData and BidnStateData are never called please suggest me solution for that what changes should i do to make call.

$(document).ready(function){
 country();
}
 function country(){
  $(".autosuggest").select2({
            minimumInputLength: 1,
             placeholder: "Select Item",
             allowClear: true,                
            ajax: {
                type: "POST",
                url: 'country.aspx/BindCountryData',
                async : false,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",                    
                data: function(term) { 
                return {
                        country: term
                        };
                    },
                results: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {                                
                                text: item.completeName,
                                slug: item.slug,
                                id: item.id

                            }})};}}});}}


 $('.autosuggest').change(function () {
            searchState();
        });

 function searchState(){
 $(".State").select2({
            minimumInputLength: 1,
             placeholder: "Select State",
             allowClear: true,                
            ajax: {
                type: "POST",
                url: 'state.aspx/BidnStateData',
                async : false,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",                    
                data: function(term) { 
                return {
                        state: term,
                        countryId : $('.autosuggest').val()
                        };
                    },
                results: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {                                
                                text: item.completeName,
                                slug: item.slug,
                                id: item.id

                            }
                        })
                    };
                }
            }
        });    
            }}
4
  • and... what is the problem ? Commented Jun 29, 2017 at 4:23
  • when i make ajax call to load data on change of country for state is not working. Commented Jun 29, 2017 at 4:29
  • could your url in the ajax call be wrong ? 'country.aspx/BidnCountryData' ==> Bidn instead of Bind ? Have you tried the url elsewhere to make sure it's working ? Commented Jun 29, 2017 at 4:33
  • nope url is BindCountryData its just mistake here to write spell of it.and it is working if i m not using select2 Commented Jun 29, 2017 at 4:37

1 Answer 1

1

I've been using the following approach in my projects:

1) Load select elements at initial stage, and bind onChange action:

    <select class="selectcombusca" name="zone_id" onChange="carregacidades($('option:selected',this).val());">
         <option value="#">Select State</option>
         <option value="1">State 1</option>
         <option value="2">State 2</option>
    </select>

    <select class="selectcombusca" name="cidade_id">
         <option value="#">Select City</option>
         <option value="1">City 1</option>
         <option value="2">City 2</option>
    </select>

2) Apply select2 to initial elements:

    $(".selectcombusca").select2();

3) Function to load cities based on the selected state, triggered on the select change:

    function carregacidades(zone_id) {
        $.ajax({
            url: your-url,
            type: 'post',
            dataType: 'json',
            data: 'zone_id=' + zone_id, //from the selected option
            beforeSend: function() {
                $('select[name=\'cidade_id\']').hide();
                $('select[name=\'cidade_id\'] + .select2').hide();
                //I like to hide the inital element so the user can undestand there's a call being made, avoiding multiple changes on the element.
                $('select[name=\'cidade_id\']').after('<span class="loading">Loading Indicator<span>'); //I also like to put some kind of loading indicator, like a spinner
            },
            complete: function() {
                $('.loading').remove(); //remove the loading indicator
                $('select[name=\'cidade_id\']').show(); //show DOM element
                $("select[name=\'cidade_id\']").select2().val('#'); //rerender select2 and set initial option
                $('select[name=\'cidade_id\'] + .select2').show(); //show select2 element
            },
            success: function(json) {
                //create the new options based on the call return
                html = '<option value="#">Cidade</option>';
                if (json['cidade'] && json['cidade'] != '') {
                    for (i = 0; i < json['cidade'].length; i++) {
                        html += '<option value="' + json['cidade'][i]['cityId'] + '">' + json['cidade'][i]['cityName'] + '</option>';
                    }
                }

                $('select[name=\'cidade_id\']').html(html); //replace select options on DOM
            },
            error: function(xhr, ajaxOptions, thrownError) {
                //handle error
            }
        });
    };

In short: by changing the select element, I hide the element that will receive the new information, make the call, add then add the information to DOM (still hidden). Finally, rerender the select2 element with the new options and then show it.

I hope this helps you.

Sign up to request clarification or add additional context in comments.

4 Comments

In my case even to load country also ajax request is not called
Give me a fiddle or a link to your page and I'll take a look.
can we use select2.js into VS2010?
According to nuget.org/packages/Select2.js, you can. NuGet is a Visual Studio extension and they offer select2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.