javascripthttpgetresponsetext

JavaScript GET responseText


I'm still learning the basics of JavaScript, and I'm trying to make a simple GET Http Request to return information from an API, but the responseText won't return. Here's the code:

var xhr = new XMLHttpRequest();
xhr.open('GET', "https://api.apithis.net/dictionary.php?define=hi", true);
xhr.send();
console.log(xhr.responseText)


Solution

  • It is because you get response a bit later. So you need to handle it async. To make this, u need to handle response in callback function, that will be fired at the moment you get response.

    I reccomend you to use at least JQuery - it helps at start. https://api.jquery.com/jquery.get/

    if u still whant it using xhr (before xhr.send), i think it can be using:

    xhr.onreadystatechange = function () { console.log(this.responseText) }