Search code examples
jqueryjsongetjson

.autocomplete() data with remote json


I have some troubles whith .autocomplete function. What i have:

<script type="text/javascript">

$( ".search" ).autocomplete({
      source: [{label:'link label1', searchLink:'http://link1.com'},
               {label:'link label2', searchLink:'http://link2.com'},
               {label:'link label3', searchLink:'http://link3.com'}],
      select:function(e,ui) { 
      location.href = ui.item.searchLink;
}
});
</script>

And i need put this json content to direct file and read data from it with this aoutocomplete data:

{
{label:'link label1', searchLink:'http://link1.com'},
{label:'link label2', searchLink:'http://link2.com'},
{label:'link label3', searchLink:'http://link3.com'}
}

Can somebody help me with it?) Maybe some way with $.getJSON() will be wery great solution:)


Solution

  • Basically below is what you need to do.

    $("#autocomplete").autocomplete({
                    delay: 500,
                    minLength: 3,
                    source: function(request, response) {
                        $.getJSON("JSON file name", {                       
                            q: request.term,
                            page_limit: 10
                        }, function(data) {
                            // data is an array of objects and must be transformed for autocomplete to use
                            var array = $.map(data, function(m) {
                                return {
                                    label: m.lable,
                                    searchLink: m.searchLink
                                };
                            });
                            response(array);
                        });
                    }
                });
    

    Below post explains how to use remote JSON with auto complete.

    http://salman-w.blogspot.com/2013/12/jquery-ui-autocomplete-examples.html#example-3

    It has complete code as well