Search code examples
javascripthtmljquery-select2

the processResult in select2 do not working


I use select2 loading remote data I send an ajax request and get the response correctly but the processResult don't run and nothing will be show

the javascript code :

var formatProduct= 
function(product) {
    console.log("formatProduct");
    if (product.loading) return product.text;
    var markup =  '<div class="product-to-compare" data=' + product.id + '>' + product.name + '</div>' ;
    return markup;
  }
var formatProductSelection = 
function (product) {
console.log("formatProductSelection");
return product.name || product.text;
}
$(".js-data-example-ajax").select2({
    placeholder: "Search for product",
    minimumInputLength: 2,
    ajax: {
        url: '/product/ajax_product_list/',
        dataType: 'json',
        quietMillis: 300,
        data: function (params) {
            var id = $('#product-no-1').attr('data') ;
            return {
                key: params,
                id: id
            };
        },
        processResults: function (data) {
        return {
            results: data.items
        };     
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatProduct, // omitted for brevity, see the source of this page
  templateSelection: formatProductSelection // omitted for brevity, see the source of this page
});    

and the JSON that my controller return as a response :

{
"items": [
  {"id": "55dd980c8242b630cfaf4788", "name": "sallll"},
  {"id": "55d58d7a8242b62c6b88504e", "name" : "inja"}, 
  {"id": "55d58d558242b62c6b88504d", "name": "salam"}
  ]
}

Solution

  • You should rename your JSON to return text instead of name.

    Note that if you're using an older version of select2 (<4) you should use results instead of processResults.