I am trying to fetch a joke using XMLHTTPRequest from a random joke generating API as practice.
Here is my code
<script>
const xhr = new XMLHttpRequest();
xhr.open('get', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json')
const joke = JSON.parse(xhr.response)
xhr.onload = function () {console.log(xhr.responseText)}
xhr.send();
</script>
and the error message i get is: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()
Funny thing is if I do JSON.parse(xhr.response) and save it to a variable, it works perfectly fine. What am I doing wrong in my script?
You're trying to parse the response before receiving the response. (AJAX is asynchronous.) You need to handle the response in the onload handler, just like you already are when you try to log it to the console:
const xhr = new XMLHttpRequest();
xhr.open('get', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function () {
const joke = JSON.parse(xhr.response);
console.log(joke);
}
xhr.send();