How can Select2 dropdown load results via AJAX
Asked Answered
E

5

11

I've got a simple select2 box which loads a dropdown menu.

But what's the best way to reload the dropdown menu each time the select menu is opened with the results of an AJAX call? The ajax call would return

<option value=1>
<option value=2>

and so on

I've look through the AJAX examples on the select2 docs but it looks a little overcomplicated for what I need. TIA

Eyeglass answered 13/11, 2012 at 14:8 Comment(2)
Could you give us a little more context? It is hard to understand your question now.Ovalle
Take a look here brytestudio.com/blog/….Yeaton
P
10

Assume u have html

   <p>
    Hidden field value set in the following format:
    <br />
    <em>'34:Donnie Darko,54:Heat,27:No Country for Old Men'
    </em></p>
<input type='hidden' id="e6" style="width: 500px;" value="34:Donnie Darko,54:Heat,27:No Country for Old Men"  />
<br /> <button id="save">Save</button>
<p>
After it's initialised, the hidden field value will change to:<br />
<em>'34,54,27'</em>
<br />
That is the value sent to the server
</p>​

​and for select2 Ajax

function MultiAjaxAutoComplete(element, url) {
    $(element).select2({
        placeholder: "Search for a movie",
        minimumInputLength: 1,
        multiple: true,
        id: function(e) { return e.id+":"+e.title; },
        ajax: {
            url: url,
            dataType: 'json',
            data: function(term, page) {

                return {
                    q: term,
                    page_limit: 10,
                    apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
                };
            },
            results: function(data, page) {
                alert(data);
                return {
                    results: data.movies
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });
};

function formatResult(movie) {
    return '<div>' + movie.title + '</div>';
};

function formatSelection(data) {
    return data.title;
};



MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');

$('#save').click(function() {
    alert($('#e6').val());
});

​Try doing multiajax call with this ! Refer - http://jsfiddle.net/JpvDt/112/

Peachey answered 4/1, 2013 at 12:33 Comment(1)
Could you tell me what is data.movies here? How will the JSON file look like? Thanks.Woman
B
3

Try this:

    $(document).ready(function () {
        $('#Registration').select2({
            placeholder: 'Select a registration',
            allowClear: true,
            ajax: {
                quietMillis: 10,
                cache: false,
                dataType: 'json',
                type: 'GET',
                url: '@Url.Action("GetItems", "ItemsController")', //This asp.net mvc -> use your own URL
                data: function (registration, page) {
                    return {
                        page: page,
                        pageSize: 100,
                        registration: registration,
                        otherValue: $("#OtherValue").val() // If you have other select2 dropdowns you can get this value
                    };
                },
                results: function (data, page) {
                    var more = (page * pageSize) < data.total; // whether or not there are more results available
                    return { results: data.dataItems, more: more }; // notice we return the value of more so Select2 knows if more results can be loaded
                }
            },
            formatResult: FormatResult,
            formatSelection: FormatSelection,
            escapeMarkup: function (m) { return m; }
        });
    });

    function FormatResult(item) {
        var markup = "";
        if (item.name !== undefined) {
            markup += "<option value='" + item.id + "'>" + item.name + "</option>";
        }
        return markup;
    }

    function FormatSelection(item) {
        return item.name;
    }
Bushbuck answered 23/4, 2013 at 7:8 Comment(0)
F
1

See the Loading Remote Data example on the Select2 webpage.

It will load the options in the select list dynamically using ajax every time it is opened.

$("#e6").select2({
        placeholder: "Search for a movie",
        minimumInputLength: 1,
        ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
            url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
            dataType: 'jsonp',
            data: function (term, page) {
                return {
                    q: term, // search term
                    page_limit: 10,
                    apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
                };
            },
            results: function (data, page) { // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to alter remote JSON data
                return {results: data.movies};
            }
        }
    });
Fevre answered 2/1, 2013 at 12:43 Comment(0)
G
0

If you are trying to show drop-down with pre-loaded JSON by default, so the moment you click on filed you expect drop-down with populated data to show up, without typing in a single letter, Set minimumInputLength: 0 and works like a charm.

It triggers JSON like it would be if your task is to "load JSON on focus using select2".

I have added code but due to not be able to use AJAX to retrieve JSON remotely in snippet I could not make snippet work.

Remember, this is solution you added to your code do not use one listed below. I use it to describe fix.


  $(".myContainer").select2({
    ajax: {
      url: 'myJSONpath',
      dataType: 'json',
      delay: 250,
      data: function(params) {
       return {
         q: params.term, // search term
         page: params.page
       };
      },
     minimumInputLength: 0, // so here is a trick 0 will trigger ajax call right when you click on field
     processResults: function(data, params) {
       //process your results  
     },

....and so one continue with your other properties...

Glosso answered 9/9, 2016 at 17:43 Comment(0)
F
0

This will help you

$(document).ready(function(){

 $("#selUser").select2({
  ajax: { 
   url: "getData.php",
   type: "post",
   dataType: 'json',
   delay: 250,
   data: function (params) {
    return {
      searchTerm: params.term // search term
    };
   },
   processResults: function (response) {
     return {
        results: response
     };
   },
   cache: true
  }
 });
});
Fosse answered 13/5, 2019 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.