Reputation: 1232
I am trying to get a Ajax-call made from jQuery to return a JavaScript array generated by PHP, but can't get it accessible. Here is what I am doing:
I run the following code onLoad:
$(function() {
jQuery.ajax({
url: 'retrieve.php',
success: function(data) {
},
async: false
}, "script");
retrieve.php returns the following (retrieve.php does the formatting, and echoes it out):
var data = {
"info" : [{
"title": "Title",
"description": "Description"
}],
"playlist" : [
{
"title": "In This Place",
"subTitle": "Excalibur",
"href": "http://localhost/manger/ny/#desemberkonsert_in-this-place",
"url": "../flv/desemberkonsert/21_in_this_place.flv",
"thumbnail": "../flv/desemberkonsert/21_in_this_place_thumbnail.png",
"time": "5:39"
}, {
"title": "Black Hole",
"subTitle": "Excalibur",
"href": "http://localhost/manger/ny/#desemberkonsert_black-hole",
"url": "../flv/desemberkonsert/22_black_hole.flv",
"thumbnail": "../flv/desemberkonsert/22_black_hole_thumbnail.png",
"time": "4:26"
}]
}
I then try to access this code using for example: $("#placeholder").text(data.playlist[0]["title"]);
The array does work when I copy and paste it directly onto the file, but when returned as a callback it fails. How do I access the returned array?
Upvotes: 1
Views: 2553
Reputation: 34340
You probably need to access your data with the [] notation, and not the . object notation:
data["playlist"][0]["title"]
Upvotes: 0
Reputation: 52372
You should return just the object, not a string of JavaScript which assigns the object to a name. That's NOT a JSON response.
Your code which uses the object should be in the success handler of the ajax call, not separate code somewhere else.
Upvotes: 1