Search code examples
jqueryjsonamchartsparsefloat

amcharts need to parseFloat the values from ajax response


I am trying to create amcharts bar charts. I have the following json which is getting from json:

[
        { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
        { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
        { "option": "Germany", "percentage": 115.80,"color":"#448800"},
        { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
        { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
        { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
    ]

I am calling ajax as follows:

$("#viewResult").click(function(){

       $("#chart").show();

       var qstnId = $("div[name='pollqstn']").attr("id");
       //Ajax to load all poll results
       $.post("fetchpollresult.php", {qstnid: qstnId}, function (data) {
           drawStuff(data);
       });


   });

My fetchpollresult.php page looks like this:

$questionid = $_REQUEST['qstnid'];

 $arranstext = array();
 $arranscount = array();

 $arranscolours = array("#2175d9","#448800","#448800","#ff9900");


//find qstn text
$pollqstndetails = $DB->get_records('epoll_questions', array('id' => $questionid));


$optiondetails = $DB->get_records('epoll_answers', array('questionid' => $questionid));

foreach($optiondetails as $optval){

 $optionresponseCount = $DB->get_records('epoll_responses', array('answerid' => $optval->id,'questionid'=>$questionid));   

 $countOptresponse =  count($optionresponseCount);


 array_push($arranstext ,$optval->answertext);
 array_push($arranscount ,count($optionresponseCount));

}


 $data =array();

for($i=0;$i<count($arranstext);$i++){

$data[]  = array('option' =>$arranstext[$i],'percentage'=>$arranscount[$i],'color'=>$arranscolours[$i]) ;
}

$optionnoresponseCount = $DB->get_records('epoll_responses', array('answerid' => 0,'questionid'=>$questionid));   

$data[]  = array('option' =>"NA",'percentage'=>count($optionnoresponseCount),'color'=>"#ff9900") ;


echo json_encode($data);

I am getting response as:

        [
            { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
            { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
            { "option": "Germany", "percentage": 115.80,"color":"#448800"},
            { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
            { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
            { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
        ]


Than I have a function calling in ajax response:

   function drawStuff(val){ 


    // RADAR CHART
    chart = new AmCharts.AmSerialChart();
chartData =val; //assigning ajax response
    chart.dataProvider = chartData;
    chart.categoryField = "option";
    chart.startDuration = 3;
    chart.sequencedAnimation = false;

    // VALUE AXIS
    var valueAxis = new AmCharts.ValueAxis();
    valueAxis.axisAlpha = 0.15;
    valueAxis.minimum = 0;
    valueAxis.dashLength = 3;
    chart.addValueAxis(valueAxis);

    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.type = "column";
    graph.colorField = "color"
    graph.valueField = "percentage";
    graph.fillAlphas = 0.6;
    graph.balloonText = "[[value]] litres of beer per year";
    chart.addGraph(graph);

    // WRITE
    chart.write("chart");
}        

But in this case it is not working. When I hard code it on the same page it works fine.

What I understand is this:

var chartData = 
        [
            { "option": "Czech Republic", "percentage": 156.90,"color":"#2175d9"},
            { "option": "Ireland", "percentage": 131.10,"color":"#ff9900"},
            { "option": "Germany", "percentage": 115.80,"color":"#448800"},
            { "option": "Australia", "percentage": 109.90,"color":"#2175d9"},
            { "option": "Austria", "percentage": 108.30,"color":"#2175d9"},
            { "option": "UK", "percentage": 99.00,"color":"#2175d9"}
        ]

I need to parseFloat the json percentage values.

How can I parseFloat only percentage pair such as 156.90,131.10.... from that json and pass as chartData??

I am getting am chart as follows:

enter image description here


Solution

  • There are a few reasons why the chart does not show up.

    1) You're not specifying content type for jQuery's AJAX call. This way you get a plain text response which is not converted to array. It's the fourth's parameter in $.post() function.:

    $.post("fetchpollresult.php", {qstnid: qstnId}, function (data) {
               drawStuff(data);
           }, "json");
    

    2) Simple typo. You have "options" for categoryField in chart code, while "option" (singular) in data.

    Just change the categoryField accordingly:

    chart.categoryField = "option";
    

    3) You are assigning chart object in an unitianalized variable. This might confuse some older browsers. Simply add var before assignation to initialize chart variable:

    var chart = new AmCharts.AmSerialChart();
    

    Here's the full code:

    $( "#viewResult" ).click( function() {
    
      $( "#chart" ).show();
    
      var qstnId = $( "div[name='pollqstn']" ).attr( "id" );
      //Ajax to load all poll results
      $.post( "fetchpollresult.php", {
        qstnid: qstnId
      }, function( data ) {
        drawStuff( data );
      }, "json" );
    
    } );
    
    function drawStuff( chartData ) {
      var chart = new AmCharts.AmSerialChart();
      chart.dataProvider = chartData;
      chart.categoryField = "option";
      chart.startDuration = 3;
      chart.sequencedAnimation = false;
    
      // VALUE AXIS
      var valueAxis = new AmCharts.ValueAxis();
      valueAxis.axisAlpha = 0.15;
      valueAxis.minimum = 0;
      valueAxis.dashLength = 3;
      chart.addValueAxis( valueAxis );
    
      // GRAPH
      var graph = new AmCharts.AmGraph();
      graph.type = "column";
      graph.colorField = "color"
      graph.valueField = "percentage";
      graph.fillAlphas = 0.6;
      graph.balloonText = "[[value]] litres of beer per year";
      chart.addGraph( graph );
    
      // WRITE
      chart.write( "chart" );
    }