Reputation: 1364
I'm trying to load my JSON Data into my script after an ajax call, but I can't seem to be getting it right.
I have a Javascript library that loads a set of music by having a set of JSON data. For example, this is how loading the script with a few songs would look like:
<script>
Amplitude.init({
"songs": [
{
"name": "Song Name 1",
"artist": "Super Dj",
"album": "2018 Super Hit",
"url": "songs/1.mp3",
"cover_art_url": "../album-art/2018superhit.png"
},
{
"name": "Song Name 2",
"artist": "Super Dj",
"album": "2018 Super Hit",
"url": "songs/2.mp3",
"cover_art_url": "../album-art/2018superhit.png"
}
]
});
</script>
Now, I'm trying to fetch the songs list data
from my database using an ajax call, to populate this list of songs dynamically. PHP-wise, it's all good and the data is fine. However, on the ajax call, the Amplitude.init
does not work when I add my JSON data
to it. The code below will give you a better idea of what I mean:
$(".mu-container").click(function(e){
e.preventDefault();
var albumId = $(this).attr("data-album");
$("#musicContainer").fadeIn();
$("#playerRibbon").fadeIn();
$.ajax({
url: "includes/app/load_music.php",
type: "POST",
data: "album_id="+albumId,
dataType: 'JSON',
success: function(data)
{
Amplitude.init({
"songs": [
data
]
});
},
error: function(err)
{
alert(err);
}
});
});
Finally, here's my PHP code which returns the JSON data, that I want to load into Amplitude.init
after the ajax call is made:
//Database connection done above
$data = array();
foreach($songs as $song){
$data[] = array("name" => $song['title'], "artist" => $song['artist'], "album" => $song['album_title'], "url" => $song['url'], "cover_art_url" => $song['album_art']);
}
echo json_encode($data); //If I run the php as a standalone with a test ID, it works just fine
Upvotes: 0
Views: 94
Reputation: 54831
Use
Amplitude.init({
"songs": data
});
Because data
is already an array of objects.
Upvotes: 1