Using Google Chart Tools to pass an array filled with data

My current project involves creating a chart with Google Chart Tools.

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'Month');
    data.addColumn('number', 'Money');
    data.addRows([
        [<%= @months %>, <%= @money %>] 
        ]);

    var options = {
      title: 'Title'
    };

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

When attempting to pass arrays for @months and @money, the chart does not display as expected. How should I handle this situation?

UPDATE

After using Gon and implementing the setCell function in a loop, the issue is now resolved and the chart appears correctly.

Answer №1

To handle data in json format, utilize the respond_to block. It is used to return a json hash containing an array of data values.

def months_monies
  respond_to |format|
    format.json {render :json => @post}
    # The post is a Ruby hash that gets converted into json string
    format.html #months_monies.html.erb
  end
end

Imagine having @post as

{:a => {"January" => 1000}, :b => {"April" => 1222}}

To access this from a javascript block, you would need to make an AJAX call to

http://localhost:3000/months_monies.json

Here's an example using jQuery:

$.get("http://localhost:3000/controller/months_monies.json",function(post){
  post.a.January # => 1000
  post.b.April   # => 1222
});

If @post happens to be an array (which might be the case for your scenario), the process is quite similar. Let's say

@post = [{'january' => 1000}, {'february' => 1111}]

You would then use post[0].january and post[1].february within the $.get block to retrieve the values.

I hope this explanation proves helpful.

Answer №2

I recently came across a predicament when attempting to pass a ruby array to the Google chart API. Despite my efforts, I couldn't figure out how to handle a missing or null series value in Ruby. Surprisingly, this issue didn't seem to interfere with your problem at all.

troubleshooting Google chart API and Ruby array problems

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 the node generated from a document fragment

Suppose I add a document fragment to the DOM in the following way: const ul = document.querySelector("ul"); const fruits = ["Apple", "Orange", "Banana", "Melon"]; const fragment = new DocumentFragment(); ...

Minimize the number of axios requests made every time a Vue component is displayed

I am relatively new to Vue, so please bear with me as I may not have all the knowledge in this area. Within one of my child components (Product_Collection.vue), I am making an axios request to retrieve products from my Shopify store using their GraphQL ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

Prevent the previous function from executing using Jquery

$(document).on('touchstart click', function (){ $('#box').hide(); }); if(isset($_GET['s'])){include(//another page);} By including another page, the document click functionality $('#box').hide(); will be di ...

Is it possible to effortlessly update all fields in a mongoose document automatically?

Take for instance the scenario where I need to update a mongoose document in a put request. The code template typically looks like this: app.put('/update', async(req,res) => { try{ const product = await Product.findById(req.body.id) ...

Error! React is unable to find the window object

I recently added the "react-speech" package to my application in order to incorporate text-to-speech functionality. However, upon importing the package, I encountered an error that has been challenging to resolve despite extensive research. Any assistance ...

Setting a value for the identifier just one time

I've been grappling with an issue that's been on my mind for some time now. There are 14 divs on my webpage, and I need each one to be given a random ID (ranging from 1 to 14) every time the page loads. These divs all share the class ".image-box ...

"Enable real-time editing with inline save/submit feature in

I'm struggling to figure out how to extract the modified content from a CKEditor instance and send it to a URL. I've been referencing something like this: but I can't seem to determine how to save the changes. Is there a way to post the up ...

Tips for efficiently utilizing both client-server side rendering and static generation rendering in web development

I am looking to implement static generation for top products using getStaticProps. Currently, there are sections in my rendering that do not require static generation, such as comments and related products. Here is the full code snippet: export default fu ...

"Searching for the index of a clicked element? Here's how to do

I am trying to determine the index of a clicked anchor element in my navigation using jQuery. However, when I use the following code snippet, I always get zero in the console: $('.navigation ul li a').click(function(e) { e.preventDefault(); ...

"I aim to ensure that my HTML, CSS, and JavaScript project is designed to be highly responsive

Bootstrap implementation on my project is causing issues with mobile view and the positioning of my divs. Take a look at my code below: table { border-collapse: collapse; margin: auto; position: absolute; width: 60%; height: 60%; ...

Retrieve documents from MongoDB that were created within the last week and return a count of 0 for any days in which no documents were created

I need to extract documents from the last 7 days stored in my Mongo Database. I have successfully retrieved data in the desired format, where specific dates and the number of tickets created on those dates are returned: { "datesUsed": { ...

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...

Characters that have been escaped are showing up when adding them to an HTML element

Through an AJAX call, I am fetching HTML code and appending it to an existing HTML element. However, the appended code includes escaped characters, leading to broken HTML with elements appearing scattered like this: Contact Us ▸<\/a><\ ...

Guide to sending various dates in the Check-in and Check-out sections on the website https://www.expedia.co.in/ using Python with Selenium

Currently developing a basic code to input and select arrival place, departure place, arrival date, and departure date on the Expedia website. Everything seems to be working fine except for the issue where the arrival date and departure date are displayin ...

Rendering on the server side using Material UI 1 in combination with Node.js and React

Issue: Unable to load styles initially through server-side rendering. Despite following the documentation, the styleSheets variable remains empty. In my Navigation component, I utilize JSS and withStyles. According to the documentation, using withStyles s ...

Display the precise outcome for each division following a successful AJAX callback

I’m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

Refresh the page excluding any <script> elements

I am looking to display a page without actually running its JavaScript code, while also injecting my own script and providing the user with a perspective similar to that of a bot. One approach I have considered is loading the page via ajax, stripping out ...

Issue with substitution of string placeholders in SQLite Ruby Gem

Having a bit of trouble with this code snippet: database.execute("SELECT * FROM #{table} WHERE id=#{id}") Each time I try running it, I keep getting an error message saying unrecognized token: "]" (SQLite3::SQLException). I have experimented with vari ...

Instructions for implementing tooltips on a pie chart slice when hovering with the mouse pointer, using the canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cw = canvas.width; var ch = canvas.height; ctx.lineWidth = 2; ctx.font = '14px verdana'; var PI2 = Math.PI * 2; var myColor = ["Gr ...