<div class="grid--cell fl1 lh-lg">
<div class="grid--cell fl1 lh-lg">
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, <a href="/help/reopen-questions">visit the help center</a>.
</div>
</div>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2012-12-03 01:36:48Z" class="relativetime">7 years ago</span>.</div>
</div>
</aside>
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() {
$.ajax({
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) {
console.log('error');
}
});
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?
</div>
If you have Firebug, you set a breakpoint here:
$('#caches').append($('<p>' + data[0].name + '</p>'));
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))
).
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.
$('#caches').append($('<p/>').text(data[0].name));
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.