Nikita TSB
Nikita TSB

Reputation: 460

.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:)

Upvotes: 0

Views: 625

Answers (2)

Thangaraja
Thangaraja

Reputation: 956

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

Upvotes: 3

Joshua Burleson
Joshua Burleson

Reputation: 26

Try writing a callback to work with the data;

$.getJSON('getSource.url',function(data){
       /* Work with your data here */
})

you may find jQuery UI autocomplete with objects useful

Upvotes: 0

Related Questions