Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2: Results not showing using AJAX

I am having trouble getting the results to show up in the 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 the request returns the expected JSON: Javascript Console

[

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

]

I believe the results: function(data, page) { ... } is not being called, since I put an alert there and nothing happened.

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

like image 220
blaze Avatar asked Jun 16 '13 20:06

blaze


1 Answers

I guess you're returning json instead of jsonp,

so try changing the line dataType: 'jsonp' to dataType: 'json', or even removing the whole line.

I've experienced the same before. json result is screened out by this criteria, even if the expected JSON is actually returned, very possibly because json and jsonp are seen as two different formats

PS: This is more like a comment, but since i can't comment on your question, please bear with me

like image 196
JK ABC Avatar answered Oct 05 '22 01:10

JK ABC