How to use Select2 with JSON via Ajax request?

melvnberd picture melvnberd · Jan 4, 2014 · Viewed 193.6k times · Source

My Select2 3.4.5 is not working with JSON data.

Here is my input box on HTML:

<input class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />

…and my JavaScript

$(".itemSearch").select2({
    placeholder: "Search for an Item",
    minimumInputLength: 2,
    ajax: {
        url: "/api/productSearch",
        dataType: 'json',
        quietMillis: 100,
        data: function (term, page) {
            return {
                option: term
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total;
            return {
                results: data.itemName,
                more: more
            };
        }
    },
    formatResult: function (data, term) {
        return data;
    },
    formatSelection: function (data) {
        return data;
    },
    dropdownCssClass: "bigdrop",
    escapeMarkup: function (m) {
        return m;
    }
});

I made an API with Laravel 4 which returns a value whenever I type anything on my text box.

Here's the result if I type "test" on my text box:

[{"itemName":"Test item no. 1","id":5},
{"itemName":"Test item no. 2","id":6},
{"itemName":"Test item no. 3","id":7},
{"itemName":"Test item no. 4","id":8},
{"itemName":"Test item no. 5","id":9},
{"itemName":"Test item no. 6","id":10},
{"itemName":"Test item no. 7","id":11}]

I can't add the result to my Select2 dropdown. I think formatSelection and formatResult are causing the problem because I don't know what parameter should be placed on it. I don't know where to get those parameters like container, object and query and the values it should be returning, or is my JSON response is wrong?

Answer

Tolo Palmer picture Tolo Palmer · Feb 6, 2014

Here you have an example

$("#profiles-thread").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: URL,
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.completeName,
                        slug: item.slug,
                        id: item.id
                    }
                })
            };
        }
    }
});

It's quite easy