Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
  ]
}
like image 656
MDK Avatar asked Sep 20 '25 06:09

MDK


1 Answers

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.

like image 171
uri2x Avatar answered Sep 22 '25 19:09

uri2x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!