Sorry, I am relatively new to Javascript and I should have been more clear with my code.
I realized that one of my variables was in the wrong scope so it kept returning as undefined.
I was making two AJAX requests, and I thought i could return the value from the first and pass it through to the second. This question helped me understand my problem: How do I return the response from an asynchronous call?
this is my javascript now:
$('span').on('click', function(){
$('#s_title').empty();
$("#playlist_title").empty();
$("#viito_list").empty();
var p_title = $(this).html();
$("#playlist_title").append(p_title);
var id = $(this).data("id");
var artistsList = []
$.ajax({
url: "/songs/"+id,
dataType: "json",
success: successCallback
})
function successCallback(data){
for(var i = 0; i < data.length; i++){
function msToTime(duration) {
var seconds = parseInt((duration/1000)%60),
minutes = parseInt((duration/(1000*60))%60)
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return minutes + ":" + seconds ;
}
artistsList.push(data[i].artists[0].name);
$("#s_title").append("<tr> <td>" + data[i].name + "</td>" + "<td>" + data[i].artists[0].name + "</td>" + "<td>" + msToTime(data[i].duration_ms) + "</td>" + "<td><span class='glyphicon glyphicon-remove song-select'></span>" + "</td> </tr>")
}
randomArtist = artistsList[Math.floor(Math.random()*artistsList.length)];
getWeird(randomArtist)
}
function getWeird(rando){
$.ajax({
type: "GET",
url: "/songs_echowrap?artist_name=" + rando,
dataType: "json"
}).success(function(data) {
$("viito_list").empty();
for(var i = 0; i < data.length; i++){
$("#viito_list").append("<tr> <td>" + data[i].title + "</td>" + "<td>" + data[i].artist_name + "</td> </tr>")
}
});
}
});