0

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 
0

1 Answer 1

0

You are not inserting your 'mylocation' variable correctly. You currently have it as part of the string.

Use this instead:

xhttp.open("GET", "http://api.geonames.org/search?q=" + mylocation + "&username=kennsully", true);

Also, pass 'responseText' to your 'myFunction' function:

if (this.readyState == 4 && this.status == 200) {
    var res = this.responseText;
    myFunction(res);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it, nothing changed
Also, pass 'responseText' to your 'myFunction' function. I have updated my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.