Autocomplete taking data from a json of a url

Asked

Viewed 135 times

0

I have this jquery

  <script>
    $(document).ready(function($){
        $('[id="franchise"]').autocomplete({
          source: "/ajax_calls/search/",
          minLength: 3,
          open: function(){
              setTimeout(function () {
                  $('.ui-autocomplete').css('z-index', 99);
              }, 0);
          }
        });
    });
  </script>

which performs the autocomplete function, taking the data from the "/ajax_calls/search/" url. This URL, has the data in list form, as follows:

['OPCAO 1', 'OPCAO 2', ...]

And everything works normally... search the data correctly and bring in the autocomplete field..

But now I changed the page and it is bringing me the data in a slightly different way. It brings all the information inside Objects:

{
    "objects": ['OPCAO 1', 'OPCAO 2', ...]
}

With this change, the autocomplete has stopped working.. How can I adjust my jquery to be able to read this new data provision?

1 answer

1


Before it was coming as an array and now as a JSON. So you should use a function in source receiving Response as JSON and returning the array within objects, filtering the array with what was typed in the field:

$(document).ready(function($){
  $('#franchise').autocomplete({
   source: function (request, response) {
      $.getJSON("/ajax_calls/search/", function (data) {
         response(data.objects.filter(function(e){
            return ~e.indexOf(request.term);
         }));
      });
    },
    minLength: 3,
    open: function(){
        setTimeout(function () {
            $('.ui-autocomplete').css('z-index', 99);
        }, 0);
    }
  });

});

Another way is to pull the whole array at once with a single request and put in the source Autocomplete. This way there will be no request to the server every time something is entered in the field:

$(document).ready(function($){
  $.getJSON("/ajax_calls/search/", function (data) {
     var fonte = data.objects;
     $('#franchise').autocomplete({
      source: fonte,
       minLength: 3,
       open: function(){
           setTimeout(function () {
               $('.ui-autocomplete').css('z-index', 99);
           }, 0);
       }
     });
  });
});
  • Man, I would’ve taken you up on that.. But I realized now that actually the autocomplete is bringing ALL the content of the page and is not 'filtering' by what I write in the field.

  • You said you’re returning the object

  • This... brings the whole object. And not just the items that match the typing

  • 1

    Edited response. Now it should work

  • 1

    I added a second form that I think is even better because it doesn’t put too much on the server.

  • 1

    Good!! Thank you very much

Show 1 more comment

Browser other questions tagged

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