M Argus Chopin Gyver M Argus Chopin Gyver - 2 months ago 8
Ajax Question

Can't show the array to charts

I got a problem using Highcharts with ajax..

I'm make a

datasource
for giving the highcharts an array..

This is the
datasource


function reportPertanyaan1()
{
$result = [];
$this->load->model("surveymodel");
for ($point=1; $point <=10 ; $point++) {
array_push($result, $this->surveymodel->GetData("1",$point));
}

echo json_encode($result);
}


And here's the ajax code that receive the array

$.ajax({
url: site_url+"datasource/reportPertanyaan1",
success: function(data){
console.log(data);
pertanyaan1(data);
}
});


From the
console.log(data)
, I get this kind of array
[2,1,0,1,1,0,1,0,0,0]


And then, from that ajax, I call
pertanyaan1
function. This is the code

function pertanyaan1(jawaban){
$('#container1').highcharts({
chart: {
type: 'line'
},
title: {
text: ''
},
xAxis: {
categories: ['1', '2', '3','4', '5', '6','7', '8', '9','10']
},
yAxis: {
title: {
text: 'Banyak Data'
}
},
series: [{
name: 'Pertanyaan 1',
data: jawaban
}],
});
}


And the code is not showing the chart. But it's doubled the
xAxis
label look like this

enter image description here

But, when I'm replace the
data: jawaban
to
data: [2,1,0,1,1,0,1,0,0,0]
. The chart can show the data..

Any help apriciated

Answer

Actually you are getting JSON from your ajax call. You need to define it as Js object. And don't send your data as array. Send your data as object.

Try this:

$data= [];
$this->load->model("surveymodel");
for ($point=1; $point <=10 ; $point++) { 
    array_push($data, $this->surveymodel->GetData("1",$point));
}

$result = new stdClass();
$result->data = $data;
echo json_encode($result);

And get data like:

$.ajax({
    url: site_url+"datasource/reportPertanyaan1",
    success: function(result){
        var resultData = JSON.parse(result);
        pertanyaan1(resultData.data);
    }
});