theHeman
theHeman

Reputation: 505

How to fetch JSON data from HTML DIV on same page for Highcharts?

I am trying to render a Highchart which uses JSON data as its source. However instead of storing it in a different file or webpage, it gets created (from MYSQL queries) in a HTML division on the same page. What changes can I make to the following code so that it will read the JSON data from the required div (let us call it JSONContainer):

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

I tried getElementByID('JSONContainer')in place of 'data.json' but I guess that is not the correct way to do it. What can I do?

EDIT: This is my code:

$.getJSON("getElementById(JSONContainer)", function(json) {
    options.xAxis.categories = json[0]['data']; //rendering X Axis
    $.each(json, function( index, value ) {
             options.series[index-1] = value;  //Making sure we skip first as that is X Axis
    }); 
    chart = new Highcharts.Chart(options);
});

Upvotes: 1

Views: 1127

Answers (1)

Sachin
Sachin

Reputation: 978

You dont need to make $.getJSON to get the data which is already on the html div.

if your data is something like this below

<div id="JSONContainer">[{"name":"LOG_DATE","data":["2015-09-08","2015-09-09"]},{"name":"a","data":[30.5‌​,87.5]},{"name":"b","data":[55.5,82.4]},{"name":"c","data":[82,57.46]},{"name":"d‌​","data":[82.4,87.4]}]</div>

Just do this

var json = JSON.parse($('#JSONContainer').text());

options.xAxis.categories = json[0]['data']; //rendering X Axis
$.each(json, function( index, value ) {
    options.series[index-1] = value;  //Making sure we skip first as that is X Axis
}); 
chart = new Highcharts.Chart(options);

PS:The " around the keys and values are important as JSON parse needs that.

Hope it helps!

Upvotes: 3

Related Questions