I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code:
$(document).ready(function() {
$("#producto").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:3,
ajax: {
url: 'http://foo.foo/listar.json',
dataType: 'jsonp',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table class='product-resultado'><tr>";
if(product.img != undefined) {
html += "<td class='product-image'><img src='"+product.img+"'/></td>";
}
html += "<td class='product-info'>";
html += product.text + "<br />";
html += product.precio_costo + " CRC <br />";
html += "Existencias: " + product.existencias;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
return product.text;
}
Upon checking the Javascript Console, I can confirm that the request is returning the expected JSON response:
[
{ "text":"Foo Product", "img":"#", "precio_costo": 45, "existencias":0, "id":2 }
]
I suspect that the results:function(data, page) { ... }
isn't triggering as intended, as I attempted an alert there and it didn't show up.
The process seems stuck, awaiting the results: