Hi im new to JSON so im not surprised that its been a slight uphill battle but i believe im 1 line of code from being able to put JSON behind me today and i just cant quite crack it
but i cant seem to get the syntax correct within my script:
var obj = new Object();
var obj = $.getJSON("/getimage.php?path=" + artist + " - " + title);
console.log(obj);
var cover = new Object();
var cover = obj.responseData.results[0].unescapedUrl
console.log(cover);
console confirms the obj variable is being passed the JSON information including the “responseText”.
error i am getting is “Uncaught TypeError: Cannot read property ‘results’ of undefined”
AJAX calls are asynchronous; i.e. at the time your code fires the data probably hasn’t returned yet. Which is why $.getJSON has a callback function, you should use that instead:
var obj = $.getJSON("/getimage.php?path=" + artist + " - " + title, function(data) {
var cover = data.results[0].unescapedUrl
console.log(cover);
});
(or make the call synchronous, but 999 out of 1000 times that’s a bad idea)
let me expand on the entire function although i dont think its relivent
//Load2 Function
function Load2() {
xmlhttp2.open("GET","http://www.radiopayback.com/previous.php",false);
xmlhttp2.onreadystatechange = function() {
if(xmlhttp2.readyState == 4) {
var xmlDoc2=xmlhttp2.responseXML;
var x=xmlDoc2.getElementsByTagName("entry");
for (i=0;i<x.length;i++) {
var artist = x[i].getElementsByTagName("artist")[0].childNodes[0].nodeValue;
var title = x[i].getElementsByTagName("track")[0].childNodes[0].nodeValue;
var obj = $.getJSON("/getimage.php?path=" + artist + " - " + title, function(data) {
console.log(obj);
var cover = data.results[0].unescapedUrl;
console.log(cover);
});
document.getElementById(i).innerHTML="<a href='http://grooveshark.com/#/search?q=" + artist +" - "+ title + "' target='_blank'>" + artist +" - "+ title + "</a>";
}
}
}
xmlhttp2.send(null);
}
Anyway, why are you using xmlhttp in the outer loop and jQuery in the inner loop? This should also work:
function Load2() {
$.get('http://www.radiopayback.com/previous.php', function(data) {
var x=data.getElementsByTagName("entry");
for (i=0;i<x.length;i++) {
var artist = $('artist', x).text();
var title = $('track', x).text();
$.getJSON("/getimage.php?path=" + artist + " - " + title, function(data2) {
var cover = data2.responseData.results[0].unescapedUrl;
console.log(cover);
});
$('#'+i).html("<a href='http://grooveshark.com/#/search?q=" + artist +" - "+ title + "' target='_blank'>" + artist +" - "+ title + "</a>");
}
}
}
i actually just gave up on JSON an hour or so ago and decided to do all the heavy lifting in PHP with a regex and then add another child element to the XML.