When processing data from a json file, the variable remains unassigned

My code involves reading data from a JSON file using D3, and then passing it to another function. Here's an example:

<!doctype html>
<html lang="en>
<head>
    <meta charset="utf-8">
    <title>Sample venn.js demonstration</title>
</head>
<style>
div {
    max-width: 300px;
    height: 400px;
    margin: 0;
    padding: 0;
}
</style>
<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="../venn.js"></script>


<script>
    var sets = [{}];
    d3.json("json", function(data) 
    {  
       sets=data;        // successful read
    });

    alert(sets);    // I need this alert to pass the value to div.datum(sets) for it to not be null.
    var div = d3.select("#weighted_example")
    div.datum(sets).call(venn.VennDiagram())
</script>
</html>

Here's the content of the JSON file:

[ { "sets": [0], "size": 1958 }, { "sets": [1], "size": 1856 }, { "sets": [2], "size": 1297 }, { "sets": [0, 1], "size": 220 }, { "sets": [2, 0], "size": 123 }, { "sets": [2, 1], "size": 139 } ]

I'm encountering an issue where seemingly unrealistic null values are passed if I don't include the alert(sets) in the d3.json() function, even though logially the value should have been assigned based on the successful read. Any thoughts on how to troubleshoot or fix this error?

Answer №1

d3.json is an asynchronous function, so there's no guarantee that the sets will be ready when you reach the div.datum line.

If you're seeing it work with alert, it's because alert pauses JavaScript execution, giving sets enough time to have a value assigned.

To ensure your datum code runs after the sets are ready, place it inside the d3.json block.

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

Build a photo carousel similar to a YouTube channel

Is there a way to create an image slider similar to the one on YouTube channels? I've noticed that when there are multiple videos on a channel, YouTube displays them in a slider with back and forth buttons to navigate through the videos that aren&apos ...

"Discover the method to access values within an associative array or object in an Ember template by utilizing a

When working with Ember, the traditional syntax for looking up array values by key is to use the .[] syntax. For example: {{myArray.[0]}} However, I have encountered an issue when trying to perform a lookup on an associative array. Even though I have a s ...

Move the displayed output in a two-dimensional space

Explore this straightforward example showcasing a cube centered at the world's origin. The camera captures the cube directly, making it appear in the center of the rendered 2D image with only its front face visible. I desire the ability to adjust the ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

Vue: updating data on the server by sending it through an axios.put request

Managing user account information is a key feature of my application. Users have the ability to edit their details by simply clicking on the edit button, which triggers two different containers to display depending on whether the edit mode is activated or ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

Having trouble inputting text into the text area using Selenium WebDriver with C#

Here is the original code snippet: I am having trouble entering text in the text box below. Can you please help me figure out how to enter text in this text box? <td id="ctl00_cRight_ucSMS_redSMSBodyCenter" class="reContentCell" ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

In JavaScript, if a string matches a property in an array, then the array can be reordered with the

Currently, I am utilizing an Angular 5 pipe to manipulate an array before displaying it using ngFor. The array consists of all active users, and my goal is to ensure that the user who is currently logged in always appears at the beginning of the array so ...

io.emit is unable to send messages to all connected clients

Struggling to implement a feature in a socket.io game where players can leave the game, I'm facing an issue with io.emit only notifying the departing player. Here's the snippet from my socket.js: io.on("connection", sock => { sock.on(&ap ...

What does the "listen EACCESS localhost" error in the code signify and why is it occurring?

const express = require('express'); const morgan = require('morgan'); const host = 'localhost'; const port = 3000; const app = express(); app.use(morgan('dev')); app.use(express.static(__dirname + '/public&ap ...

"Exciting new feature: Magnific Popup Gallery now includes a convenient

My current challenge involves a client request for the ability to download images from a gallery by clicking on a download button. I am wondering if there is a way to incorporate this download button within the gallery popup. Specifically, the button shoul ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...

The contents of an array will be modified when the corresponding array that holds its value is altered

I have encountered a puzzling issue that I can't seem to comprehend. Specifically, I am dealing with a service array as follows: this.awesombarservice.Selected = [{id:1, value="20180101"}],[{id:1, value="20180103"}] After initializing another array ...

Error: Attempting to access property 'getElementById' of an undefined variable is not allowed

I encountered an error when trying to run a code that I didn't create. The error message is as follows: TypeError: Cannot read property 'getElementById' of undefined Module.<anonymous> C:/Users/src/index.js:6 3 | import App from &a ...

Exploring the syntax of ReactJS state management with setState

Trying to wrap my head around the following syntax in my React app. I am looking to understand how the code inside setState() works. this.getSomePromise().then( // resolve callback function someImg => this.setState(prevState => ( ...

The second request made with $.ajax is bypassed

I have been working on integrating the Google Maps JavaScript API and attempting to update a heat map when a user clicks on a specific div element. The latitude and longitude data used for the heatmap are fetched from local JSON files. While I have success ...