Select2 with AJAX

Asked

Viewed 9,080 times

6

For some reason my Select2 using AJAX to fill it is not working. When I put a Debugger in the code, it does not enter the method result: and also returns no error.

HTML:

<input type="hidden" class="bigdrop select2-offscreen" name="e7" id="e7" tabindex="-1">

Javascript:

$("#e7").select2({
    placeholder: "Buscar",
    minimumInputLength: 3,
    ajax: {
        url:"/perfil/buscarBancas",
        dataType: 'jsonp',
        quietMillis: 100,
        data: function (term, page) { // page is the one-based page number tracked by Select2
            debugger;
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page
            };
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            debugger;
           alert("some error");
        },
        results: function (data, page) {
            debugger;
            var more = (page * 10) < data.total; // whether or not there are more results available
            // notice we return the value of more so Select2 knows if more results can be loaded
            debugger;
            return {results: data.results, more: more};
        }
    },
    formatResult: movieFormatResultText, // omitted for brevity, see the source of this page
    formatSelection: movieFormatSelectionText, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

function movieFormatResultText(movie) {
    var markup = "<table class='movie-result'><tr>";
    markup += "<td class='movie-info'><div class='movie-title'>" + movie.text + "</div>";   
    markup += "</td></tr></table>";
    return markup;
}

function movieFormatSelectionText(movie) {
    return movie.text;
}

JSON:

[
   {
      "total":"20",
      "results":[
         {
            "id":"1",
            "text":"ACAFE"
         },
         {
            "id":"2",
            "text":"ACAPLAM"
         },
         {
            "id":"3",
            "text":"ACEP"
         },
         {
            "id":"4",
            "text":"ADVISE"
         },
         {
            "id":"219",
            "text":"Aeron\u00e1utica"
         },
         {
            "id":"239",
            "text":"AMIGA P\u00daBLICA"
         },
         {
            "id":"253",
            "text":"ANBIMA"
         },
         {
            "id":"5",
            "text":"AOCP"
         },
         {
            "id":"6",
            "text":"ASPERHS"
         },
         {
            "id":"7",
            "text":"BIO-RIO"
         },
         {
            "id":"8",
            "text":"CAIP-IMES"
         },
         {
            "id":"9",
            "text":"CAJU\u00cdNA"
         },
         {
            "id":"257",
            "text":"CANPASS"
         },
         {
            "id":"165",
            "text":"CCEV - UFMT"
         },
         {
            "id":"10",
            "text":"CCV-UFC"
         },
         {
            "id":"255",
            "text":"CEC"
         },
         {
            "id":"11",
            "text":"CECIERJ"
         },
         {
            "id":"12",
            "text":"CEFET-AL"
         },
         {
            "id":"13",
            "text":"CEFET-BA"
         },
         {
            "id":"14",
            "text":"CEPERJ"
         }
      ]
   }
]

He comes to seek, but returns nothing.

  • When accessing the url /perfil/buscarBancas in hand, something happens?

  • Return this JSON that I posted @rodrigorigotti

  • Look at your Datatype name as JSONP and the correct one was json

4 answers

4


Follow an example from Lect2.

HTML

<input type="hidden" class="select2" />

Javascript

$(".select2").select2({
    placeholder: "Buscar",
    minimumInputLength: 3,
    ajax: {
        url:"/echo/json/",
        dataType: 'json',
        quietMillis: 100,
        data: function (term, page) {
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total;
            return {results: data.results, more: more};
        }
    },
    escapeMarkup: function (m) { return m; }
});

JSON example of the expected response of the AJAX request

{"total":"20","results":[{"id":"1","text":"ACAFE"},{"id":"2","text":"ACAPLAM"},{"id":"3","text":"ACEP"},{"id":"4","text":"ADVISE"},{"id":"219","text":"Aeron\u00e1utica"},{"id":"239","text":"AMIGA P\u00daBLICA"},{"id":"253","text":"ANBIMA"},{"id":"5","text":"AOCP"},{"id":"6","text":"ASPERHS"},{"id":"7","text":"BIO-RIO"},{"id":"8","text":"CAIP-IMES"},{"id":"9","text":"CAJU\u00cdNA"},{"id":"257","text":"CANPASS"},{"id":"165","text":"CCEV - UFMT"},{"id":"10","text":"CCV-UFC"},{"id":"255","text":"CEC"},{"id":"11","text":"CECIERJ"},{"id":"12","text":"CEFET-AL"},{"id":"13","text":"CEFET-BA"},{"id":"14","text":"CEPERJ"}]};

http://jsfiddle.net/2ZYm5/

  • I believe that is the answer to my problem, I have not yet been able to carry out the tests, following your choice, it was worth.

2

Use the type dataType: 'json' as Anderson posted. If you use jsonp, it means that you are trying to execute a cross-Domain request, and in case you need to add in your url:

?callback=?

http://api.jquery.com/jQuery.ajax/

"jsonp": Loads in a JSON block using JSONP. Adds an extra "? callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string Parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

As it says there, you should add callback to your url.

0

Really this Lect2 is all problematic, I tried to use a while ago but I could not. I ended up changing to the solution presented in the link below:

http://jqueryui.com/autocomplete/

Works perfectly and is very easy to use.

On the website below an example of use in the survey:

http://guiadatv.net

I hope I’ve helped.

  • 1

    I did not want to change the plugin because it is already used in the project, if there is no other way even I will change.

0

The code below worked for me:

<!DOCTYPE HTML PUBLIC>
<HTML>
 <HEAD>
  <TITLE> Select2 </TITLE>
    <link href="select2/select2.css" rel="stylesheet" type="text/css" />
    <script src="//code.jquery.com/jquery-latest.min.js"></script>
    <script src="select2/select2.js"></script>
    <script src="select2/select2_locale_pt-BR.js"></script>

 <script>
        $(document).ready(function() { 
            $('#e7').select2({
                minimumInputLength: 2,
        ajax: {
            url: "teste.json",
            dataType: 'json',
            data: function (term, page) {
                return {
                    q: term
                  };
            },
            results: function (data, page) {
                return {
                    results: data
                };
            }
        }
    });

  });
    </script>
</head>
<body>
    <input type="hidden" id="e7" style="width:300px" class="input-xlarge" />
</body>
</html>

And the response in json format with this formatting:

[{
    "id": "1",
    "text": "resultado1"
  }, {
    "id": "2",
    "text": "resultado2"
  }
]

I hope you solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.