Problem: I want to get the data from the REST API call and assign it to a variable and use that as an input for another Function or Purpose.
Function:
function getSongName(id, callback) {
var apikey = {My_TOKEN};
var fetchInformation = "https://www.googleapis.com/youtube/v3/videos?key=" +apikey +"&fields=items(snippet(title" +"))&part=snippet&id=" +id;
$.getJSON(fetchInformation, function (jsonData) {
fullname = jsonData.items[0].snippet.title;
callback(fullname);
});
}
I am calling this function in another place with
var title = getSongName(youtubeID, function(name) {
console.log("song name is :"+name);
});
I get the value in console.log as required. Now I want to use this title in
z.innerHTML = '<b>' + title + 'num: ' + j + '</b>';
Here j
is coming from another place so I cannot use it inside the "getSongName" call.
Is there a way not just to do console.log
inside but actually assign the "name" to another variable and use it as what I want above?
I don't know if there is another way of doing this that I have not come across but any help will be appreciated.
SOLVED -----------STEPS MENTIONED BELOW
function getSongName(youtubeID, idForPlayer,i, z, callback) {
var apikey = {My_TOKEN};
var fetchInformation = "https://www.googleapis.com/youtube/v3/videos?key=" +apikey +"&fields=items(snippet(title" +"))&part=snippet&id=" +id;
//$.ajaxSetup({'async':false}); WILL return the value for each loop and not do it asynchronously which had me pulling my hair out. P.S. this was the reason only one value was being returned
$.ajaxSetup({'async':false});
$.getJSON(fetchInformation, function (jsonData) {
debugger;
var fullname = jsonData.items[0].snippet.title;
boolean = false;
if (fullname) {
boolean = true;
if (boolean){
console.log("song name inside the gerSongName loop is: " + i +" ", fullname);
callback(fullname);
}
debugger;
}
else {
debugger;
console.log("No song name");
}
});
}
Then inside another function which is run in a loop I called the above function to get me the value.
getSongName(youtubeID, idForPlayer,i, z, function(name) {
z.innerHTML = '<b>' + name + '</b>';
debugger;
document.getElementById('elementTagID').appendChild(z);
});
Hope this helps someone else. Thank you.