I have the below javascript code which supposedly returns geoid of a given location. I tested it in Chromium browser with CORS plugin. It retrieves the ID but I am unable to reach the value from outside of the function.
I am new to javascript but I read those link1, link2 and searched before posting my question.
Here is the fiddle
What am I missing?
EDIT: Thanks to moderators they redirected my question on the right track. So how can I fix my code to bypass asyncronous call?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
var mylocation = 'istanbul'
xhttp.open("GET", "http://api.geonames.org/search?q= + mylocation + &username=kennsully", true);
xhttp.send();
function myFunction(arg) {
var xmlDoc = arg.responseXML;
var geoid = xmlDoc.getElementsByTagName("geonameId")[1].childNodes[0].nodeValue;
// document.write(geoid); // when uncommented it prints the id 891501
// console.log(geoid);
return geoid;
};
var geoid = myFunction();
console.log(geoid);// <= Uncaught TypeError: Cannot read property 'responseXML' of undefined
at myFunction