Take the 2-minute tour ×

I'm a newb so go easy:

I can't figure out why this $.ajax function won't append my xhr data to the correct place.

    // gets the cache data from our php file
function getcaches() {
        method: 'get',
        url: "php/findcache.php",
        dataType: "json", // return type data is json
        success: function(data){ // <-- data is in json format
            //parse the json data
            $('#caches').append($('<p>' + data[0].name + '</p>'));
        error: function(data) {
    return false;   

That's the relevant javascript. I know the data is being stored properly in the object because i can see it in firebug...

[OU0397] => stdClass Object
        [code] => OU0397
        [name] => A Mighty Oak in the Open
        [location] => 28.527633|-81.125167
        [type] => Virtual
        [status] => Available

I just don't understand what I'm doing wrong. Any pointers?

share|improve this question

closed as too localized by Jack, Chris Gerken, lserni, bpeterson76, Graviton Dec 3 '12 at 1:36


Why do you think you have a [0]? –  Ignacio Vazquez-Abrams Apr 24 '12 at 1:49
Is it data[0].name or data.name? –  Aleksandar Vučetić Apr 24 '12 at 1:50
I've tried both, neither give me a response –  pizoelectric Apr 24 '12 at 1:57
the data object has three entries though, I only pasted one to save space. How should I address those? –  pizoelectric Apr 24 '12 at 1:57
What you see in firebug is not a JSON –  Dr.Molle Apr 24 '12 at 2:12
show 1 more comment

2 Answers

The code sample has XSS vulnerability (what if name has "<" characters in it?).

Do not add text values to HTML without proper HTML encoding. You can use jQuery's text() method to set element text instead of concatenating strings.


It could be one of the reasons why your output is incorrect.

You can debug your jQuery CSS selector from Firebug or with Chrome developer tools by executing $('#caches') and it will return an array of matched elements.

share|improve this answer
add comment

If you have Firebug, you set a breakpoint here:


And then you inspect data. Your debug data showed OU0397 as the key; due to PHP's json_encode, that means you are likely given a dictionary. Dictionaries are traversed in a different manner (e.g. for i in data { ... }).

You could also consider changing your PHP to return only the first result; this simplifies your JavaScript and reduce network overhead (e.g. use json_encode(current($data))).

share|improve this answer
add comment
