Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
Why I cant JSON.parse a string from an API (Error msg: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>))

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!