visualizing JSON data in Phant with the power of D3.js

I am currently exploring the use of d3.js to visualize data that is stored within the sparkfun cloud, which is an IoT cloud platform. I came across an example that utilizes Google Chart for visualizing data from sparkfun cloud by using a specific script:

<!DOCTYPE html>
<html>
  <head>
    <!-- EXTERNAL LIBS-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://www.google.com/jsapi"></script>

    <!-- EXAMPLE SCRIPT -->
    <script>

      // onload callback
      function drawChart() {

        var public_key = 'dZ4EVmE8yGCRGx5XRX1W';

        // JSONP request
        var jsonData = $.ajax({
          url: 'https://data.sparkfun.com/output/' + public_key + '.json',
          data: {page: 1},
          dataType: 'jsonp',
        }).done(function (results) {

          var data = new google.visualization.DataTable();

          data.addColumn('datetime', 'Time');
          data.addColumn('number', 'Temp');
          data.addColumn('number', 'Wind Speed MPH');

          $.each(results, function (i, row) {
            data.addRow([
              (new Date(row.timestamp)),
              parseFloat(row.tempf),
              parseFloat(row.windspeedmph)
            ]);
          });

          var chart = new google.visualization.LineChart($('#chart').get(0));

          chart.draw(data, {
            title: 'Wimp Weather Station'
          });

        });

      }

      // load chart lib
      google.load('visualization', '1', {
        packages: ['corechart']
      });

      // call drawChart once google charts is loaded
      google.setOnLoadCallback(drawChart);

    </script>

  </head>
  <body>
    <div id="chart" style="width: 100%;"></div>
  </body>
</html>

Instead of utilizing Google Chart, I wish to utilize d3.js for plotting the data as it offers greater flexibility. However, I encountered difficulties with the implementation and attempted to extract data from the website using d3.js json extractor, based on information from related questions (1, 2):

var data1;
var url = "https://data.sparkfun.com/output/dZ4EVmE8yGCRGx5XRX1W.json"

d3.json(url, function (json) {
         if (error) return console.warn(error);
     //data1 = json;
     data1=json;
     consol.log(data1)
             //code here
                     })

Unfortunately, this approach did not yield the desired results. As I am relatively new to d3.js and JavaScript, I believe there may be key pieces of information missing in my implementation. Any guidance or directions on how to proceed would be greatly appreciated. Thank you!

Answer №1

When attempting to capture the error, make sure to include it as the primary parameter in the nameless function:

d3.json(url, function (error, json) {
    //first argument -----^
    if (error) return console.warn(error);
    data=json;
    console.log(data)
    //additional code here
 })

Note that in d3.json, "error" is actually the first argument, not the second.

A simpler option is to eliminate the "error" altogether:

d3.json(url, function (json) {
    data=json;
    console.log(data)
    //more code here
 })

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

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

A guide on implementing moment.js in EJS views to display the user's local time instead of the server's

I've set up Moment js on my server using app.locals to pass it around. app.locals.moment = require('moment'); Despite trying to call the local() function when showing the time, it continues to display the time based on the server's ti ...

PHP Pagination with AJAX and MySQL

I'm currently working on a website that functions as a forum, where posts are displayed dynamically using ajax. Upon user login, they encounter a 'orderby' dropdown selection, allowing them to choose the order of the posts. Select Menu < ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

"Integrating JavaScript files into HTML using Flask: A step-by-step guide

I have created an HTML page with a JavaScript section where I am importing various other .js files: <script type="module"> import * as THREE from "../build/three.module.js"; import { OrbitControls } from ...

Transmit and receive Json data but unable to interpret the response

I am working on an application that requires me to send JSON code through web requests. I am able to establish the connection and send and receive data using GET, POST, PUT, and DELETE methods. However, although I believe I am receiving JSON code in respon ...

Running into trouble importing an ES module in Node.js during a migration

Currently, I am in the process of developing a straightforward application for my personal project using ExpressJS. To manage database changes, I have opted to utilize sequelize ORM. My current objective is to rollback a migration, and to achieve this goal ...

Utilize JSON or an environment file to pass dynamic values to an npm script

I've been working on setting up an npm script for deploying react apps (specifically using create-react-app). However, I'm facing a challenge in setting the S3 bucket url string in either an environment variable or JSON file. This way, I can easi ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

What are some alternatives to dynamicComponentLoader in Angular 2 RC5?

I am currently developing an Angular 2 app in RC5 where I need to dynamically load Components. In the past, in RC1, I achieved this by using dynamicComponentLoader as shown below: @Component({ moduleId: module.id, selector: 'generic-component&ap ...

Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source. My attempt with the .attr() ...

Discover the significance of a data attribute's value for effective comparisons

I have a loop that generates random numbers and positions to create 4 answer choices for users. Now, I am trying to determine the value of the clicked button and compare it to the position of the correct answer. However, whenever I try to do this, it retu ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

The conditional statement of either/or

I need to create a button that changes based on whether checkboxes are checked. If none are checked, I want to show a disabled button. If one or more are checked, I want to display a different button. JavaScript $("#checkAll").change(function ( ...

When copying text from React-PDF Display, the values may appear altered or varied

This snippet of text was excerpted from a brief SHA provided at the git summit. Generated using React-pdf, this is a PDF document with some interesting quirks. Although the displayed text reads as 4903677, it changes to •G07THH when copied. The font ...

Tips on adjusting the width of columns in a Google chart?

Is there a way to adjust the width of the bars in a Google chart column? I attempted to set 'bar: { groupWidth: "20%" }' but it had no effect on the chart. https://i.sstatic.net/jM3o0.png I really want to make the bars thinner. Below ...

A guide to retrieving the Java exception behind a ScriptException in JSR-223

My current setup involves running Javascripts through the JSR-223 script engine within JRE6. These scripts have the ability to access Java code and objects. In case an exception is generated by the Java code called from a JavaScript, the ScriptEngine will ...

Event listeners cannot be applied to elements that are returned from a function

I have been grappling with a puzzle for an extended period of time. In my code, I have an entity called the "To-Do List". Within this list, I am attempting to enable functionality for the buttons labeled "doneButton" and "deleteButton" using the "addEventL ...