0

I am having great difficulty in successfully parsing a JSON file to use within JQuery UI autocomplete

Please see my dev page: http://www.zyredesign.com/autocomplete

The JSON isn't organised as well as I would have hoped as the items keys are ID's eg:

{"140":"Abarth", "375":"Acura" }

Etc....

Here is my javascript attempt:

$(document).ready(function() {


    $('#cars').autocomplete({
        source: function()
        {


            $.getJSON('json.json', function(data)
            {
                cars_array = new Array();

                $.each(data, function(k, v) { 

                    cars_array.push(v);

                 })

                alert( cars_array);

                return cars_array;
            })


        },
        minLength: 3,
        focus: function( event, ui ) {},
        select: function( event, ui ) {
            $('#suggestions').html(ui);

            return false;
        }
    });

});

/*
function get_json()
{
var items = new Array();

$.getJSON('json.json', function(data) {
  var items = [];


  alert(  eval ("(" + data + ")") ); 

 // $.each(data, function(key, val) {
    //items.push('<li id="' + key + '">' + val + '</li>');

 // });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

return items;
}
*/

Any help would be greatly appreciated, thanks!

1 Answer 1

2

The function you've supplied for the source: attribute doesn't return a value. The $.get() function does, but that won't reach the source attribute.

    source: function()
    {
        $.getJSON('json.json', function(data)
        {
            cars_array = new Array();
            $.each(data, function(k, v) { 
               cars_array.push(v);
            })
            return cars_array;
        })
        //You need to return something here
    }

Also, it may be an issue that you're using an asynchronous call to the json file in a synchronous pattern. In other words, consider this:

    $.getJSON('json.json', function(data)
    {
        cars_array = new Array();
        $.each(data, function(k, v) { 
           cars_array.push(v);
        })

        //Now you definitely have the cars so you can do the autocomplete
        $('#cars').autocomplete({
            source:cars_array,
            minLength: 3,
            focus: function( event, ui ) {},
            select: function( event, ui ) {
            $('#suggestions').html(ui);
            return false;
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.