Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Select2 dropdown load results via AJAX

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

like image 267
raharley Avatar asked Nov 13 '12 14:11

raharley


People also ask

What is Ajax dropdown?

AjaxDropDownList is a dropdownlist control that has the following features: Fetch data asynchronously in the background from a server source, with no postback.

How do I set Select2 values?

To set selected value of jQuery Select2 with JavaScript, we call val and then trigger . Then we set its value with val to the option with value 0. Finally, we call trigger with 'change' to update the drop down to show the value we set.

How can make AJAX call in jQuery?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.

What Select2 dropdown?

By default, Select2 will attach the dropdown to the end of the body and will absolutely position it to appear above or below the selection container. Select2 will display the dropdown above the container if there is not enough space below the container, but there is enough space above it.


2 Answers

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;
    }
like image 198
ping Avatar answered Oct 09 '22 10:10

ping


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/

like image 45
Sri Avatar answered Oct 09 '22 10:10

Sri