4

I am displaying Highcharts graph on a haml template using jQuery/javascript. Here is a snippet showing the standalone graph from the demo code in HighCharts site:

:javascript

  $(document).ready(function() {
    $("#tabs").tabs();
    new Highcharts.Chart({
      chart: {
        renderTo: 'volume_chart'
      },
      title: {
        text: 'Logarithmic axis demo'
      },
      xAxis: {
        tickInterval: 1
      },
      yAxis: {
        type: 'logarithmic',
        minorTickInterval: 0.1
      },
      tooltip: {
        headerFormat: '<b>{series.name}</b><br />',
        pointFormat: 'x = {point.x}, y = {point.y}'
      },
      series: [{            
        data: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512],
        pointStart: 1
      }]
    });
  });

This works fine. Now I am trying to set the series data from a ruby/rails array in the show.html.haml file like so:

...
- data_array        = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
...
:javascript

  $(document).ready(function() {
  ...
      series: [{            
        data: "#{data_array}",
        pointStart: 1
      }]
    });
  }); 

This gives me the following error:

undefined method `to_js' for [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]:Array

How can I pass data_array from my ruby/rails code to the javascript/jquery code?

Appreciate any help.

Thanks.

Bharat

2 Answers 2

5
require 'json'

...

"#{data_array.to_json}"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I independently found the following: 1. Do not name this array "data" something as this will interfere with jQuery's remote data transfer mechanism. 2. Having renamed this array as "test_array" I could say what you have above, i.e. "#{test_array.to_json" or "#{test_array.inspect}" or just "#{test_array}", all of which work. I do appreciate your time.
0

Hey in HAML there is no need to use to_json

   :javascript
     $(document).ready(function() {
       ...
       series: [{            
         data: #{ruby_array},
         pointStart: 1
       }]
     });
    }); 

will perfectly work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.