JQuery Autocomplete with an AJAX call to a remote JSON

  • 0
I'm posting this because it took me ages to figure it out...
I wanted an input field with autcomplete values provided by a remote JSON. My requisites were the following:
  • No dynamic JSON request:
  • Every time the user types a letter no JSON remote call!
  • autocomplete accepts a source : data field, where data can be an URL to a remote location. The problem is that when the user is typing it keeps sending requests to the URL appending ?term=. The idea is that the filtering is done on the server side.... Not what I want... I want the filter to be done on the client side as in case when data is a local variable.
  • Also, because every JSON generation takes more than 1 second, I wanted just one, and a single one request, to the remote location.
So here the code that sorted it out:
/* Function to populate the autocomplete from a remote json. 
   Note the Ajax call which success populates the autocomplete selector
*/
function set_autocomplete(selector, jsonurl) {
    $.ajax({
        url: jsonurl,
        type: 'get',
        dataType: 'json',
        async: true,
        success: function(data) {
            //console.log(data);
            $(selector).autocomplete({
                source: data,
                minLength: 0,
            });
        }
    });
}

/* This is only called once when the page is loaded :) 
   Here the URL to the json and the selector are defined.
*/
$(function() {
    var jsonurl = "URL TO CALL";
    var selector = 'YOUR SELECTOR, e.g.: input';
    if ($(selector).is('*')) {
        set_autocomplete(selector, jsonurl);
    }
});
My JSON looks like this (note that what the user types matches the label but the input field will keep what I have in the value) :
[  
   {  
      "value":"46477",
      "label":"46477 - erererer"
   },
   {  
      "value":"46478",
      "label":"46478 - erererere"
   },
   {  
      "value":"46479",
      "label":"46479 - ererererer"
   },
   {  
      "value":"46480",
      "label":"46480 - trhteyretytryteyety"
   }
]
And the CSS (just to keep the drop down box with a fixed width and scroll bar):
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}

No comments:

Post a Comment