2

I want to load a JSON data in RoR 4 to graphic the data using Highcharts. I have in index.html.erb

{<h1 style="text-align:center" >HighCharts Test</h1>
<h1>Start</h1>
<div id="container" style="width:100%;height:400px;"></div>
<script>
   $(document).ready(function() {

    var options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };

    $.getJSON('data.json', function(data) {
        options.series[0].data = data;
        var chart = new Highcharts.Chart(options);
    });

});
</script>
<h1>End</h1>}

The data.json is in the same folder as index.html.erb.

However, it is not plotting anything when i run the code. Im very new to RoR and Highcharts. Whats the error? Thank you.

2 Answers 2

1

You need to create a controller, let say ChartsController. and write following method in charts_controller.rb

def data
  # this method is to send manually json data 
  #render json: {name: 'test',data: [2,0,9,23,2,123]}
  # or read data from a data.json file, use your custom path
  data = File.read("#{Rails.root}/app/views/charts/data.json")
  render json: data
end

and, in your view write this code.

<script src="/assets/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<h1>Start</h1>
<div id="container" style="width:100%;height:400px;"></div>
<script>  

$(document).ready(function() {
    options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };
    $.getJSON('data.json', function(data) {
        options.series = data;
        new Highcharts.Chart(options);
    });

});

<h1>End</h1>

I have tried, it works at my side, hopefully it work successfully.

Sign up to request clarification or add additional context in comments.

4 Comments

Maybe it works, but I am trying to load a JSON file (30000 rows) instead of writing manually the data in the controller. The example from Highcharts 'Preprocess data using JSON' is not working for me.
I have updated answer with both options, now It will help you.
it shows now the JSON file but no plot: [ [1,12], [2,5], [3,18], [4,13], [5,7], [6,4], [7,9], [8,10], [9,15], [10,22] ].
In case when you have many points, try to set 0 for turbothreshold parameter
1

Haven't worked with RoR yet, but my best guess will be that either your json file should be in the assets folder. (or some other folder used for static files).

The other way around (the right way, I believe) will be to have a separate controller, that will render you json file after you have requested it via js code. See this question: getting data using jquery getJSON in ruby on rails

Comments

Your Answer

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