Tomek Buszewski
Tomek Buszewski

Reputation: 7935

jQueryUI's Autocomplete doesn't understand JSON?

I have this JSON array:

[
    {"name":"Mario Kart Wii"},
    {"name":"Super Mario Galaxy 2"},
    {"name":"Super Mario Galaxy"},
    {"name":"Mario Sports Mix"},
    {"name":"Mario & Sonic at the Olympic Winter Games"}
]

Pretty much simple.

And my jQuery code:

$('#searchFieldGame').autocomplete({
        source: function(request, response) {
            console.log(response)
            $.getJSON('/index.php/search/autocomplete/'+request['term'],response)
        },
        select: function(event, ui) {
            $('#searchFieldGame').val(ui.item.value);
            $('#searchFormGame').submit()
        },
        minLength: 3
    })

My problem is - when JSON is simpler, eg:

[
    "Mario Kart Wii",
    "Super Mario Galaxy 2",
    "Super Mario Galaxy",
    "Mario Sports Mix",
    "Mario & Sonic at the Olympic Winter Games"
 ]

It works great. But if it's more like the first one, it doesn't get any results. I need to keep it like the first one, because I want more elements in every array later.

Upvotes: 1

Views: 94

Answers (2)

Kevin B
Kevin B

Reputation: 95023

If it's an array of objects, it must at least have value and/or label properties. source

[
    {"value":"Mario Kart Wii"},
    {"value":"Super Mario Galaxy 2"},
    {"value":"Super Mario Galaxy"},
    {"value":"Mario Sports Mix"},
    {"value":"Mario & Sonic at the Olympic Winter Games"}
]

If that isn't an option, you can use $.map to fix it.

$.getJSON('/index.php/search/autocomplete/'+request['term'],function(data){
    response( $.map(data,function(obj) {
        return obj.name;
    }) );
});

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

For jQuery UI autocomplete, there are only two acceptable data formats.

['item', 'item2', 'item3', ...]
[{label: 'item', value: 'itemvalue'}, {label: 'item2', value: 'itemvalue2'}, ... ]

Upvotes: 3

Related Questions