1

The below code works to send a GET API request. It returns data for a company name in a JSON HAL format within the function 'httpGet(name)'. The console.log(http.response) command does log the expected result. However, the subsequent return http.response returns 'undefined' when called in another function.

Could someone explain what I'm (obviously) doing wrong. Much appreciated!

  function httpGet(name) {
    const http = new XMLHttpRequest();
    const url = "https://api.overheid.io/suggest/openkvk/" + name + "?ovio-api-key=MYKEY" // MYKEY is equal to my API key
    http.open("GET", url);
    http.send();
    //http.onload = () => console.log(http.response);
    http.onload = function() {
      let text = http.response
      var id = text.split('id":"')[1]
      id = id.split('",')[0]
      
      const url = "https://api.overheid.io/openkvk/" + id + "?ovio-api-key=MYKEY" // MYKEY is equal to my API key
      http.open("GET", url);
      http.send();
      http.onload = () => console.log(http.response);  //returns the correct http.response as a JSON HAL repsonse
      return http.response; // returns undefined when the function is called. Example (other function): console.log(httpGet('Heineken')) returns 'undefined'
  
      }

  }
pepinstall
  • 11
  • 2
  • Does this answer your question? [Pass the value of an xhr onload function globally](https://stackoverflow.com/questions/20207405/pass-the-value-of-an-xhr-onload-function-globally) – Remi Guan Jan 15 '22 at 12:14
  • Also, have a look at [this question](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – Remi Guan Jan 15 '22 at 12:14
  • it's an async issue – MWO Jan 15 '22 at 12:15
  • Your problem is because you're trying to return something from `http.onload`, which is a *callback function*, and that means: it will only be called when your request is done. In this case, it doesn't work if you're trying to get the result from a calling to `httpGet()`. In your script, `httpGet()` doesn't contain a return statement, thus it gives you `undefined` as the result. – Remi Guan Jan 15 '22 at 12:17

0 Answers0