简体   繁体   中英

How to pass JSON data to update Highcharts Pie chart

I am trying to make an AJAX call to my server and pass in a year value. The server then fetches from a database information about different countries' economies of that year. I am then using that data to update the pie chart from Highcharts.

So my AJAX call is like so

$('#one').change(function() {
var val = $("#one option:selected").text();
var id = 'one';
$.ajax({
    type: "POST",
    url: "/sss",
    data: {val, id},
    dataType: 'JSON',
    success: function () { 
        console.log('success');
    },
    error: function (ts) {
        alert(ts.responseText);
        alert(val);
    }
  })
  .done(function (results){
    results = JSON.stringify(results);
    var chart = $('#char1').highcharts();
    chart.series[0].setData(results);
    /* chart.series[0].setData([ { name: 'USA', y: 19386200 },
    { name: 'China', y: 12059889 },
    { name: 'Japan', y: 4867528 },
    { name: 'Germany', y: 3753700 }]); */
    alert(results);
  })
});

Then my route for when I POST to /sss is

router.post('/sss', function(req, res, next){
   console.log("sss");
   var yr = req.body.val;
   console.log(yr);

   var funnn = function(year, callback){
       uploadController.getGDPfunc(year, callback);
   }

   funnn(Number(yr), function(err,results){
      if(err) console.log("err");
      else{
          //console.log(results);
          res.send(results);
      }
   });
});

So I am calling my controller function from the route and it is returning the results in the correct format. Even in AJAX, I can log the results and it looks in the correct format. If I was to copy those outputed results and paste them into chart.series[0].setData(HERE), then it would work. But only if I leave the chart.series[0].setData(results) does it not work correctly.

Any ideas why this can be? If I hardcode the data in the AJAX "done" part, then it updates properly so I do not believe that the chart rendering is the problem. I feel like it is the format of the data, but like I said it works if I was to hardcode it into the setData...So I am lost. Any ideas?

Thanks

You start with an object parsed from JSON, you shouldn't stringify it into a string again like you do here:

results = JSON.stringify(results);

Assuming that results gives you the sort of object you would expect, just remove that line so that you call setData with the proper object (array), rather than a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM