Chaitanya Vardhan Chaitanya Vardhan - 23 days ago 9
Ajax Question

not able to format json data to use it in auto complete

I wanted to use autocomplete in a text box,I am making an ajax call to get the JSON and I wanted to use it to auto-complete the text box tags,but the array items are turning out to be [object object].and hence the id attribute of the JSON is inaccessible,I wanted to know if there are any ways to get out of this problem

var items;
$( document ).ready(function() {
$("#header").load("Header.html");
$("#footer").load("Footer.html");

var url= "GetAuthorities.do";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
items=data;
});

$("#tags").autocomplete({
source:items,
label:items.id,
value:items.value
})

});


<td width="30%"><input type="text" name="IrbAppNum" id="IrbAppNum" style="width:40%"> <input id="tags"></td>


After ajax call i am getting this JSON:

[[
{"id":"1","value":"Stanford University"},
{"id":"2","value":"University of Houston"},
{"id":"3","value":"FDA"},
{"id":"4","value":"Drug Authority of Texas"}
]]

Answer

You need to modify your .done() handler a bit as follows:

var items;
$( document ).ready(function() {
    $("#header").load("Header.html");
    $("#footer").load("Footer.html");

    var url= "GetAuthorities.do";
    $.getJSON( flickerAPI, {
        tags: "mount rainier",
        tagmode: "any",
        format: "json"
    })
    .done(function( data ) {
        if(data && data.length > 0){
            items=data[0]; //grab the data which is at index 0

            //init the autocomplete widget here
            $("#tags").autocomplete({
                source:items,
                label:items.id,
                value:items.value
            });
        }
    });
});

Here we are assigning the returned data to items variable by reading the index 0 of received object and also initiating the autocomplete widget there itself as its a ajax async call. Defining it outside of .done handler will have items variable undefined and you won't get anything in your autocomplete text box's search result.