Tips for refreshing a D3.js bubble chart with live JSON data updates

Currently delving into d3 and experimenting with transforming a static bubble chart into a dynamic one that adjusts by removing or adding bubbles based on JSON changes.

I am aiming to have the JSON file refreshed every 5 seconds to update the bubble chart. I attempted to implement setInterval() with the code snippet below, although it's not functioning as intended...

var inter = setInterval(function() {
  updateData();
}, 5000);

function updateData() {
  d3.json("sample.json", function(error, data) {
    if (error) throw error;

    //receiving the json file
   root = d3.hierarchy(classes(data))
        .sum(function(d) { return d.value; })
        .sort(function(a, b) { return b.value - a.value; });
   console.log(root);
   bubble(root);

   node = svg.selectAll(".node")
       .data(root.children);

   node.exit().remove();

   //insertion of new elements from the file
   node.enter().append("g")
   .attr("class", "node")

   node.append("title")
       .text(function(d) { return d.data.className + ": " + format(d.value); });

   node.append("circle")
       .attr("r", function(d) { return d.r; })
       .style("fill", function(d) {
         return color(d.data.packageName);
       });

   node.append("text")
       .attr("dy", ".3em")
       .style("text-anchor", "middle")
       .text(function(d) { return d.data.className.substring(0, d.r / 3); });
  });
}
//==============================================================================
// updates end here

d3.select(self.frameElement).style("height", diameter + "px");

// Helper function definitions
// Fetches a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}

Verifying root in the console produced no changes

In addition, my knowledge about AJAX is limited. Is it mandatory to incorporate AJAX to update the JSON data?

If required, how can the POST method be utilized to refresh the entire JSON file?

Answer №1

Perhaps it could be due to the browser cache being the culprit. Give this a shot:

d3.json("data.json?v="+Date.now(), function(err, result) { ...

Answer №2

It seems like you are fetching a file that has static content.

d3.json("sample.json", [...]

If sample.json remains constant, your data will also remain unchanged. To update the information, you'll either need server-side processing to create a new JSON file in that location or utilize an API to retrieve dynamic values (potentially from a database). Your current code can then make use of this updated data.

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

Tips for creating a single div element on a React form

I have a form that is generated using the array map method in React. I am trying to add either 'box-one' or 'box-two' div element when clicking on the add button, but currently both div elements are being added. How can I ensure that on ...

Expanding Your jQuery Library from a Content Delivery Network

As of now, I have a jQuery hosted on my FTP along with other web files. YSlow recommends using a CDN for jQuery. However, I am wondering how I can extend that jQuery. Is it possible to add custom functions to it without being able to edit the original co ...

The W3C validator does not recognize any modifications made after jQuery and JavaScript have been applied

My goal is to ensure that my website passes all errors on the W3C Validator. I have encountered a few errors related to the alt text of images. In an attempt to address this issue, I wrote and added the following code to the <head> <script type=" ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

The filter for Woocommerce, when added through the add_filter(‘woocommerce_product_get_price’) function, does not take effect when triggered by an ajax call

I have implemented the Role Based Pricing for WooCommerce plugin to customize prices based on user roles. Although the filter works correctly when I call the functions to retrieve products, it always returns the default price value when the function is ca ...

Discover the value of $(this) while working with dynamically generated elements in jQuery

Suppose I have a dynamic list created via AJAX, with li elements: ​<ul id="dynamic-list"> <li data-label="label1" >Label 1</li> <li data-label="label2" >Label 2</li> <li data-label="label3" >Label 3</l ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Is there a way to calculate the distance in kilometers between two sets of longitude and latitude in an Android application?

Explanation: This question may sound repetitive, but I have encountered some confusion while working on a live application. The JSON data contains longitude and latitude values which I need to compare with the current coordinates. Despite attem ...

Double dragenter events triggered before dragleave in HTML5 drag and drop functionality

Currently, I'm researching HTML5 Drag and Drop functionality by using this resource. However, I've encountered an issue with the dragenter event that seems to fire twice for child elements before the dragleave event. Because of this, the dashed b ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Are certain browsers unable to play dynamically generated HTML5 audio files?

While working on my project, I encountered an issue with creating and controlling an audio element in JavaScript. The element works perfectly fine in Firefox, Chrome, and Opera; however, it fails to function properly in IE and Safari. In these browsers, ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

How can I resolve the issue of shadow.static in Three.js causing shadows to shift when the shadow.bias is adjusted? Suggestions on

So I've got a scene with some nice shadows being cast by a light, but there's this pesky static issue with the shadow. Check it out: https://i.sstatic.net/k3XIe.jpg When I try to fix it with a simple tweak like light.shadow.bias = -0.005;: htt ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

Issue with updating dropdown values in real-time in React

I am a beginner with React and I have a question regarding fetching dropdown values from the backend. Despite using async-await functions, the list is not getting populated with items. Any assistance in this matter would be greatly appreciated. Here is th ...

Using Jquery to make an Ajax request to a PHP script that retrieves JSON data

Hello, I am new to working with JSON. I have a PHP script that contains a multidimensional array, which is then encoded into JSON format like this: <?php header('Content-Type: application/json'); $lista = array ( 'Conoscenti'=&g ...