0

My code (draft):

function get_city(){
    const http = new XMLHttpRequest();
    const url='https://api.sypexgeo.net/json/';
    http.open("GET", url);
    http.send();
    console.log("Resp: " + http.responseText);
    var response_json = JSON.parse(http.responseText);
    return response_json["city"]["name_en"];
}

Could you help me understand why this script is not working on a real web site.

I mean that I can enter each string from this script into a browser's console and get a correct result.

But as soon as I try to use it on a real website, I get this error:

Resp: 
VM350:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at get_city (?utm_replace=ViarVizualizatorArhiva_TR:588)
    at replacer (?utm_replace=ViarVizualizatorArhiva_TR:637)
    at ?utm_replace=ViarVizualizatorArhiva_TR:647

As we can see, response is empty. Well, this is a mystery to me. Why should it be empty if in console it is ok?

Michael
  • 4,273
  • 3
  • 40
  • 69

1 Answers1

1

You are making an asynchronous protocol call. Your code keeps going after your .send() action, but your response could come later, or never.

You need to perform your action only when the response is received.

After your send() action, wrap your code in an event handler:

http.onreadystatechange = function () {
    //your response handler
}

See: https://medium.freecodecamp.org/here-is-the-most-popular-ways-to-make-an-http-request-in-javascript-954ce8c95aaa

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176