Troubleshooting: Issues with Parsing a JSON String from an API causing an Error (Error Message: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>))

I have been experimenting with fetching jokes using XMLHTTPRequest from a random joke generating API for practice.

Below is the code I am using:

<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>

However, when I run this code, I encounter an error message: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ().

Interestingly, if I use JSON.parse(xhr.response) and save it to a variable, the script works without any issues. Can anyone spot what I might be doing wrong in my code?

Answer №1

When dealing with AJAX, it's important to remember that the response is received asynchronously. Make sure you handle the response in the onload handler as shown below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform geojson data into an HTML table

As someone new to JavaScript, I am trying to figure out how to populate a HTML table with geojson entries like "ename" etc. Here is my current code: <table id="jsoncontent"></table> <script type="text/javascript"> window.onload = fu ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

Selecting elements with special characters in their IDs using JQuery can be done

I am facing an issue with this HTML code where the Id includes special characters: <input type="text" id="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d ...

Node and Express app making a double POST request

This particular section serves as the route code. router.post('/content', function(req, res) { var topic = req.body.inputText; console.log("topic :"+topic); //displays correctly var somedata = ""; console.log("request arrived for ...

Error encountered in CRM system using Javascript

After implementing JavaScript in CRM, I encountered an issue when trying to open a specific employee record. The error message displayed is as follows: "Unable to get property 'Value' of undefined or null reference" This error seems to only occ ...

Transformation of 3D geometric coordinates to 2D screen coordinates in Three.js

the width of the plane is set to 800 pixels: geometry = new THREE.PlaneGeometry( 800, 20, 0, 0 ); material = new THREE.MeshBasicMaterial({ color:0xFFFFFF, side:THREE.DoubleSide }); mesh = new THREE.Mesh(geometry, material); mesh.updateMatrixWo ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/compone ...

Instructions for connecting a camera to a bone or vertices on a model in A-Frame without influencing its rotation

How can I attach a first-person camera to the head of an animated GTLF model? My plan is to eliminate the model's head and combine the neck into one vertex to avoid obstructing the camera. I am curious about the process of attaching my camera to the v ...

filter out null values from JSON using gson

I am looking for a way to eliminate attributes with empty collections or null values using gson. Aiperiodo periodo = periodoService(); //periodo is obtained from a service method with various values Gson gson = new Gson(); String json = gson.toJson(period ...

Turning text into a web address

I am having trouble converting a string into a NSURL in my code. Here is what I have so far: NSString *urlString = [[NSString alloc]initWithFormat:@"http://host name/index.php?id=%@&mob=%@&name=%@&mail=%@&m=23", self.deviceId, self.pnumber ...

jQuery - "Error: fadeIn is not a valid function"

Encountering an odd issue here. Attempting to execute fadeIn() but receiving the error ".fadeIn is not a function". Here is my code: body { display:none; } <!DOCTYPE html> <html lang="en> <head> <!-- Required meta tags --&g ...

Tips for parsing JSON when a collectionView is tapped

Hello there! I am currently exploring different methods of parsing json data when a collection view is clicked and passing it to another view. The API I am using for this purpose can be found here. In my current approach, I follow these steps: I create a c ...

Problems with pipe execution in awk script causing unexpected errors

A unique challenge has presented itself to me. I have a newline separated, JSON'd output from an observation programming that runs in cron. Every 5 minutes it appends a new observation to a file. To search for any issues and retrieve the date of the ...

What is the best way to locate the relative xpath of an element that I click on a webpage using Javascript?

Is there a way to use JavaScript in order to retrieve the relative XPath of any element that I click on my page? The code provided doesn't seem to be working as expected. How can I modify it to achieve the desired result? function findElementXPath( ...

jQuery autocomplete feature is not functioning properly on dynamically generated input fields

I am encountering an issue with autocomplete on dynamically created fields. In the image attached, I have created dynamic fields by clicking on the plus sign. Autocomplete is working on the first row, but for the rest of the dynamically generated rows, au ...

PHP AJAX autocomplete - achieving precise matches

As I work on my PHP/MySQL/Ajax Autocomplete app, I am delighted by its ability to display available addresses in real-time while the user types, much like Google Maps. The application functions smoothly and displays results accurately: https://i.sstatic.n ...

Connecting to a specific mui-tab with react-router-dom

How can I link to a specific tab in my material ui-based tabs setup within a React application? I want to be able to navigate directly to a particular tab when landing on the page, but I'm struggling with integrating this functionality. Is there a way ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...

Having trouble with an error on Amazon S3 that says "ETagMissing: No access to ETag property on response"? Make sure to review the CORS configuration to expose the ETag header for a solution

Encountering an error message stating "ETagMissing: No access to ETag property on response. Check CORS configuration to expose ETag header." while attempting a multipart upload to AWS. Despite thorough research online, I have been unable to find a solution ...

Issues with WordPress forms are causing frustration

Looking for some assistance here. I am in the process of creating a one-page WordPress theme and I am struggling with getting the contact form to submit without reloading the page. All my code is in the index.php file. The PHP code for form submission is ...