SuperNinja
SuperNinja

Reputation: 1606

Understanding JSON and displaying

I have the following ajax request...

Ajax

function initUpdate()
{
    var id = $(this).attr('id').split('_')[1];
    //grab id from link update_xxxx

    //get all gallery information
    $.ajax(
    {
        type: 'POST',
        url: 'ajax/update',
        data: {"id": id},
        dataType: 'json',
        success: function(json)
        {

            //query was successful now populate form
            $("input[name='galleryName']").val(/*what goes here?*/);
        }
    });
}

That returns the following data

{
    "selected_gallery": [
        {
            "id": "4004",
            "name": "Album Proofer Sample Gallery",
            "clientRef": "205",
            "clientName": "Mike "
        }
    ]
}

How would I access "name" to insert in the val()?

Thanks!

Upvotes: 2

Views: 50

Answers (1)

David Hoerster
David Hoerster

Reputation: 28701

What have you tried? I would think you could get to it via:

json.selected_gallery[0].name

selected_gallery is a JavaScript array, so you would access the first item in the collection using [0] in order access the first item's properties.

UPDATE

You could access other items in the array if they existed:

{
    "selected_gallery": [
        {
            "id": "4004",
            "name": "Album Proofer Sample Gallery",
            "clientRef": "205",
            "clientName": "Mike "
        },
        {
            "id": "5005",
            "name": "blah",
            "clientRef": "405",
            "clientName": "Dave "
        },
        {
            "id": "6006",
            "name": "boo",
            "clientRef": "605",
            "clientName": "Doug"
        }
    ]
}

To get the second item in the array, you'd reference it as:

json.selected_gallery[1].name (or id or clientRef or ...). You can get to the third item via json.selected_gallery[2].name.

Hope this helps.

Upvotes: 4

Related Questions