Search code examples
javascriptxmlhttprequest

Why does the api responds twice even though I have called once in JavaScript using XMLHttpRequest?


When I send the request then the first response is empty then it shows the JSON response twice. How can I solve this? Any advice will be helpful. Thanks :(

Code:

function go() {
  var cat;
  var api = new XMLHttpRequest();
  var ip = document.getElementById(
    "ipBox").value;
  var finalUrl =
    "http://ipwhois.app/json/" + ip;
  api.open("GET", finalUrl);
  api.send();
  api.onreadystatechange = (e) => {
  cat = api.responseText;
  console.log(cat)
  };
}

Solution

  • readyState has multiple possible values, including "loading" and "interactive", not just "complete". Use onload instead.