0

I am using select2 (4.0.3). My code is working and is fetching the results both on page load and on search. However, after doing a remote search and selecting an item from the list, my initSelection block makes 2 more ajax calls with search param being the ID of the selected value. I only want my initselection to work when page is loaded with a prepopulated value for the dropdown. Any help is appreciated.

$(".venue-dropdown").select2({
    placeholder: "Enter venue name",
    allowClear: true,
    ajax: {
        url: $('#contextPath').val() + "/ajax/get-venue",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data) {
            return {
                //results: data.items,
                results: $.map(data, function (obj) {
                    return {
                        id: obj.uniqueName,
                        text: obj.name + ' (' + obj.postcode + ')'
                    }
                }),
            };
        },
        cache: true
    },initSelection: function(element, callback) {
        var id = $(element).val();
        if (id && id !== "") {
            $.ajax($('#contextPath').val() + "/ajax/get-venue", {
                data: {
                    search: id
                },
                dataType: "json",
                cache: false,
            }).done(function(data) {
                var result = {'id':data[0].uniqueName,'text':data[0].name};
                callback(result);
            });
        }
    },
    escapeMarkup: function (markup) {
        return markup;
    },
    minimumInputLength: 2
});

First ajax made when searching >>> get-venue?search=eh8

After selecting a option 2 ajax requests are followed

get-venue?search=sportexercisepleasanceeh89tj&_=1488967266450

get-venue?search=sportexercisepleasanceeh89tj&_=1488967266451

Ankit
  • 257
  • 1
  • 3
  • 13

0 Answers0