Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and when manually copied and pasted into the chart, it works fine. Therefore, the issue seems to be with the code not processing correctly.

http://jsfiddle.net/DNH5n/8/

google.load("visualization", "1", {
    packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);

function drawChart() {
    var dataset =     $.ajax({
        url: 'http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?page=1',
        type: 'get',
        dataType: 'jsonp',
        crossDomain: true,
        success: function (jsonObj) {
            var arr = ["[['Time', 'Humidity', 'Temp']"];
            $.each(jsonObj, function (i, tObj) {
                arr.push("['" + tObj.stationtime + "', " + tObj.humidity + ', ' + tObj.temp + ']');

            });
            arr.push("]")

            // This for debugging
            document.getElementById("demo").innerHTML = arr;
        }
    });
    var data = google.visualization.arrayToDataTable([
        dataset
    ]);

    var options = {
        title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

Answer №1

Here are a couple of key points to note:

  1. Make sure to use the result of the AJAX call, not the call itself, as input for arrayToDataTable.
  2. Parse the data from the AJAX call output and convert them into Date objects and floats.

For more information, you can refer to:

http://jsfiddle.net/K8bk3/

$.ajax({
    url: 'http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?page=1',
    type: 'get',
    dataType: 'jsonp',
    crossDomain: true,
    success: function (jsonObj) {
        var arr = [['Time', 'Humidity', 'Temp']];
        $.each(jsonObj, function (i, tObj) {
            arr.push([new Date(tObj.stationtime),  parseFloat(tObj.humidity), parseFloat(tObj.temp)]);

        });
        document.getElementById("demo").innerHTML = arr;
    var  data = google.visualization.arrayToDataTable(arr);

var options = {
    title: 'Company Performance'
};

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);        }
});

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

Obtaining JSON information with Svelte

I'm currently facing a mental block. My goal is to fetch JSON data using the Youtube API. The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided: <script> ...

Transfer the information of a selected element to a different element

Hello, I am trying to transfer content from a child element to another element. In my HTML setup, there is a hidden div named "DetailsExpanded" and multiple items called "IconWrapper". When an "IconWrapper" is clicked, I want to copy the content of its "I ...

How to implement an Angular Animation that is customizable with an @Input() parameter?

Have you ever wondered if it's possible to integrate custom parameters into an Angular animation by passing them through a function, and then proceed to use the resulting animation in a component? To exemplify this concept, consider this demo where t ...

Exploring the world of SPA: Implementing Data Transfer Objects

Considering implementing a Single Page Application (SPA) using a JavaScript framework like Angular JS. Currently, I have multiple existing Web APIs containing the necessary information for the app. I need to add another API that will handle new data and re ...

Tips for retaining the original size of an image in HTML5 canvas drawImage

function getBase64ImageData(_id) { var canv = document.createElement('CANVAS'); var context = canv.getContext("2d"); var imageElem = document.getElementById(_id); context.drawImage(imageElem, 0, 0); var dataURL = canv.toDat ...

I'm having trouble receiving a response after uploading an image on Cloudinary using React js

Once the image is uploaded using the API, it should return a response. However, I am not receiving any response through the API even after uploading the image. if (pic.type === "image/jpeg" || pic.type === "image/png") { const da ...

In react-native, when the string includes spaces, it will result in a line change

I am currently utilizing react-native in combination with styled-components. Whenever a string is typed into the text and followed by pressing the spacebar, it either results in too many line breaks or creates excessive empty spaces. An example of this i ...

An issue arose when attempting to submit data from an AngularJS form

I am having an issue with my AngularJS form that is supposed to post data to a Scalatra servlet. Unfortunately, when the form is submitted, I am unable to retrieve any form parameters in my Scalatra servlet. Here is a snippet of my code: AngularJS $scop ...

What is the best way to dissect emails using Haraka?

After delving into the haraka project (at ), I managed to successfully install it on my linux machine. Now, I'm interested in finding a comprehensive tutorial on parsing email meta headers and content body using haraka. Despite searching through their ...

Identifying Changes in Form Values Using jQuery

I am facing a challenge with a dynamic form that needs to detect the field sequence properly. Below is my JavaScript file: var i = 1; $("a.add-line").click(function(){ $("div.items").append( $('<div>').attr('id',&ap ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

javascript issue with setting the id attribute on a select option

I can't seem to set the id attribute in my select element using JavaScript. When I inspect it, the id attribute isn't showing up... Here's the first method using JS: var selectorElem = document.getElementById('selector') var ...

Slideshow feature stops working after one cycle

Hey there! I'm currently working on a function that allows for sliding through a series of images contained within a div. The goal is to cycle back to the beginning when reaching the end, and vice versa when going in the opposite direction. While my c ...

When you log a JavaScript array after making a call using $.ajax, it may return an index

I am experiencing an issue with my array of 10 elements. When I log their key, value pairs in a loop, they are correctly ordered. $.each( sArray, function(i, k) { log(i, k); // log(i, k) returns correctly // [0] ELEMENT ONE // [1] ELEMENT TW ...

Troubleshooting the 403 error in Laravel 5.2 with AJAX POST requests

I'm experiencing difficulties with Laravel 5.2, specifically when attempting an AJAX POST request, I encounter a 403 error Here is the code for the AJAX POST request: $.ajax({ headers: { 'X-CSRF-Token': $('meta[ ...

Prevent event bubbling on a link generated by an Angular directive that includes transclusion

I am currently developing a directive that adds a link to a DIV element through transclusion. However, I am facing an issue where I want to execute specific functionality when the link is clicked without being redirected to the dummy href (in this case goo ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

Utilizing PHP and JavaScript in a multi-page setting

Apologies for the length of this post in advance. I've been struggling with a coding issue for quite some time now and haven't been able to find a solution. To provide more context and help to those who might assist me, I'm including most of ...

How can datatables format a column by pulling from various sources? (Utilizing server side processing

Struggling to implement server-side processing with concatenated columns and encountering SQL errors. Came across a post discussing the issue: Datatables - Server-side processing - DB column merging Would like to insert a space between fields, is this ac ...

Issues arise with req.body being undefined when using node.js in conjunction with Express version 4.16.X and Body-Parser version

Recently, I began using node.js to construct a RESTFul API. Currently, my focus lies in inserting data through POST requests with JSON in the body. However, I encountered an issue where the req.body always returned as undefined. Upon investigating further ...