Select2: non-AJAX results

I'm having problems displaying results in Select2 using AJAX. Here 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; } 

Using the Javascript Console, I see that the request returns the expected JSON: Javascript console

[

{"text": "Foo Product", "img": "#", "precio_costo": 45, "existencias": 0, "id": 2}

]

I believe that the results: function(data, page) { ... } not called, since I put a warning there and nothing happened.

It just hangs there, waiting for the results: Hangs waiting for results

+7
source share
2 answers

I think you are returning json instead of jsonp,

try changing the line dataType: 'jsonp' to dataType: 'json' , or even deleting the entire line.

I have experienced the same thing before. The json result is checked against these criteria, even if the expected JSON is actually returned, it is very possible because json and jsonp are considered as two different formats.

PS: This is more like a comment, but since I can not comment on your question, please carry me

+11
source

I think you cannot return the ajax form for the form form., Since the ajax call is asynchronous . Process the results there yourself. or use callback functions as indicated in the link below.

see jQuery: return data after ajax success

0
source

All Articles