Nivedit Majumdar
Nivedit Majumdar

Reputation: 67

Importing JSON based remote data to Select2 using AJAX

The aim is to import data from the Controller side to a Select2 element (with multiselect toggled on). I want the setup to look something like the tags box in Stack Overflow, wherein you can begin typing a tag, select it, and select another one later.

I have been using the Select2 documentation as a reference, however the request isn't being sent to the Controller.

Select2 Documentation

My Code:

$(".jsData").select2({          
    ajax: {
        contentType: 'application/json',
        url: '<%=Url.Action("GetDataMethod","RelevantController")%>',
        type: 'POST',
        dataType: 'json',
        data: function (term) {
            return {
                sSearchTerm: term
            };
        },
        results: function (data) {
            var datajs = $.map(data, function (obj) {
                obj.text = obj.someterm; // desired field,
                obj.id = obj.someId;
                return obj;
            });
            return {
                results: JSON.parse("[" + datajs.split(",") + "]")
            };
        }
    },
    multiple: true         
});

I'm relatively new to bringing data dynamically to Select 2, so any help would be most appreciated. Thanks!

Upvotes: 2

Views: 172

Answers (1)

Nivedit Majumdar
Nivedit Majumdar

Reputation: 67

UPDATE: Found the solution, posting it here for others.

HTML

 <input class="jsData" style="width: 100%"  id="select2Data" ></input>

Javascript

              $(".jsData").select2({
                        ajax: {
                            minimumInputLength: 4,
                            contentType: 'application/json',
                            url: '<%=Url.Action("GetData","Controller")%>',
                            type: 'POST',
                            dataType: 'json',
                            data: function (term) {
                                return {
                                    sSearchTerm: term
                                };
                            },
                            results: function (data) {
                                return {
                                    results: $.map(JSON.parse(data), function (item) {
                                        return {
                                            text: item.term,
                                            slug: item.slug,
                                            id: item.Id
                                        }
                                    })
                                };
                            }
                        },
                        multiple: true
                    });

Upvotes: 1

Related Questions