mimi
mimi

Reputation: 365

Execute chartjs after an ajax call with PHP

I want to load the ChartJs Chart after an ajax call. But unfortunately, it showing Undefined variable errors for all ChartJS php variables.

Target:

Change the chart based on user select from the dropdown list, each selection option is basically a JSON link from where we fetch the data to show with chartjs.

What I have done so far:

Issues:

Here is the Javascript part:

 $(document).ready(function(){
                  $.ajax({
          url: "./url.php",
          type: "POST",
          data: {
            cur: $("#cur").val()
          },
           success: function(data) {
                    alert(data);
                        new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [<?php echo '"'.$cot_labels.'"'; ?>],
    datasets: [{ 
        data: [<?php echo $cot_values; ?>],
        label: "A",
        borderColor: "#3e95cd",
        fill: false
      }, { 
        data: [<?php echo $cot_values2; ?>],
        label: "B",
        borderColor: "#8e5ea2",
        fill: false
      } ,
      { 
        data: [<?php echo $cot_values3; ?>],
        label: "C",
        borderColor: "#085b83",
        fill: false
      }  ,
      { 
        data: [<?php echo $cot_values4; ?>],
        label: "D",
        borderColor: "#1c2925",
        fill: false
      } ,
        { 
        data: [<?php echo $cot_values5; ?>],
        label: "E",
        borderColor: "#b9801d",
        fill: false
      } 
    ]
  },
  options: {
    title: {
      display: true,
      text: '<?php echo $name; ?>'
    },
     animation: {
            duration: 0, // general animation time
        },
         hover: {
            animationDuration: 0, // duration of animations when hovering an item
        },
        responsiveAnimationDuration: 0, // animation duration after a resize
  }
});	
                }         
             });
    $('#cur').on('change', function() {
          $.ajax({
          url: "./url.php",
          type: "POST",
          data: {
            cur: $("#cur").val()
          },
           success: function(data) {
                    alert(data);
                        new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [<?php echo '"'.$cot_labels.'"'; ?>],
    datasets: [{ 
        data: [<?php echo $cot_values; ?>],
        label: "A",
        borderColor: "#3e95cd",
        fill: false
      }, { 
        data: [<?php echo $cot_values2; ?>],
        label: "B",
        borderColor: "#8e5ea2",
        fill: false
      } ,
      { 
        data: [<?php echo $cot_values3; ?>],
        label: "C",
        borderColor: "#085b83",
        fill: false
      }  ,
      { 
        data: [<?php echo $cot_values4; ?>],
        label: "D",
        borderColor: "#1c2925",
        fill: false
      } ,
        { 
        data: [<?php echo $cot_values5; ?>],
        label: "E",
        borderColor: "#b9801d",
        fill: false
      } 
    ]
  },
  options: {
    title: {
      display: true,
      text: '<?php echo $name; ?>'
    },
     animation: {
            duration: 0, // general animation time
        },
         hover: {
            animationDuration: 0, // duration of animations when hovering an item
        },
        responsiveAnimationDuration: 0, // animation duration after a resize
  }
});	
                }
          
             });
       });
       });
           <select id="cur" name="cur">
    <option value="<?php echo $euro;?>">EURO</option>
    <option value="<?php echo $pound;?>">UK</option>
   
</select>
        <canvas id="line-chart" width="800" height="450"></canvas>  

Here is the PHP Part:

 $euro = "URL";
    $pound = "URL";

//AJAX CALL
 if (isset($_POST['cur'])) {
   $cur = filter_input(INPUT_POST, 'cur', FILTER_SANITIZE_STRING);
          //Build arrays
 $cot_label_arr = array();
 $cot_value_arr = array();
 $cot_value_arr2 = array();
 $cot_value_arr3 = array();
 $cot_value_arr4 = array();
 $cot_value_arr5 = array();
   $json=file_get_contents($cur);
 $data =  json_decode($json);
  foreach ($data as $item  ) {
  $name = $item->name;
 // echo $item->newest_available_date;
  foreach($item as $value => $value_1){
    if (is_array($value_1) || is_object($value_1))
   {
    foreach($value_1  as $value_2 ){                 
         if (is_array($value_2) || is_object($value_2))
    {
             $cot_label_arr[] = date('M j Y',strtotime($value_2[0])); //pull dates
             $cot_value_arr[] = $value_2[1]; 
             $cot_value_arr2[] = $value_2[2]; 
             $cot_value_arr3[] = $value_2[3]; 
             $cot_value_arr4[] = $value_2[4]; 
             $cot_value_arr5[] = $value_2[5];                

        }
       }

     }
   }
  }
$cot_labels = array_reverse($cot_label_arr); //reverse the data for ASC
$cot_values = array_reverse($cot_value_arr); //reverse the data for ASC
$cot_values2 = array_reverse($cot_value_arr2); //reverse the data for ASC
$cot_values3 = array_reverse($cot_value_arr3); //reverse the data for ASC
$cot_values4 = array_reverse($cot_value_arr4); //reverse the data for ASC
$cot_values5 = array_reverse($cot_value_arr5); //reverse the data for ASC
//----
$cot_labels = implode('","', $cot_labels); //comma sep
$cot_values = implode(", ", $cot_values); //comma sep
$cot_values2 = implode(", ", $cot_values2); //comma sep
$cot_values3 = implode(", ", $cot_values3); //comma sep
$cot_values4 = implode(", ", $cot_values4); //comma sep
$cot_values5 = implode(", ", $cot_values5); //comma sep
 exit;
 } // End of ajax call

If I use echo $cot_values; inside the ajax call, then I get to see correct data. But chartjs is not loading with it. Here is the screenshot of what I get returned for $cot_values.

enter image description here

Not sure why I am getting undefined data error for chartjs php variables whereas I am calling the chartjs javascript after the successful ajax call. Plus why the correct data is not loading on the chart.

UPDATE: with MLStud coding

Now no longer undefined php chartjs variable error as we are using java json data. But the chart is not loading, in the place of the chart a white blank space is showing. I have tested all data for any kind of wrong format, but it was ok.

Here is the updated coding part:

PHP:

if (isset($_POST['cur'])) {     
........
$cot_labels = implode(", ", $cot_labels); //edited as it was showing date with extra ""
$cot_values = implode(", ", $cot_values); //comma sep
$cot_values2 = implode(", ", $cot_values2); //comma sep
$cot_values3 = implode(", ", $cot_values3); //comma sep
$cot_values4 = implode(", ", $cot_values4); //comma sep
$cot_values5 = implode(", ", $cot_values5); //comma sep

 // New added
 $result = array(
'cot_labels'=>$cot_labels,
'cot_values'=>$cot_values,
'cot_values2'=>$cot_values2,
'cot_values3'=>$cot_values3,
'cot_values4'=>$cot_values4,
'cot_values5'=>$cot_values5,
'name'=>$name

   );
  print_r(json_encode($result));
   exit;
   } // End of ajax call

Javascript + HTML :

   $(document).ready(function(){
        var ctx = document.getElementById("myChart").getContext('2d');
                  $.ajax({
          url: "./url.php",
          type: "POST",
          data: {
            cur: $("#cur").val()
          },
           success: function(data) {   
             alert(data);
             var datos = JSON.parse(data);       
                 var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: datos.cot_labels, ///in this way you access the data of the returned json
                        datasets: [{
                            data: datos.cot_values,///in this way you access the data of the returned json
                            label: "A",
                            borderColor: "#3e95cd",
                            fill: false
                        }, {
                            data: datos.cot_values2,
                            label: "B",
                            borderColor: "#8e5ea2",
                            fill: false
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: data.name
                        },
                        animation: {
                            duration: 0, // general animation time
                        },
                        hover: {
                            animationDuration: 0, // duration of animations when hovering an item
                        },
                        responsiveAnimationDuration: 0, // animation duration after a resize
                    }
                });	
                }         
             });
    $('#cur').on('change', function() {    
          $.ajax({
          url: "./url.php",
          type: "POST",
          data: {
            cur: $("#cur").val()
          },
           success: function(data) {         
               var datos = JSON.parse(data);  
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: datos.cot_labels, ///in this way you access the data of the returned json
                        datasets: [{
                            data: datos.cot_values,///in this way you access the data of the returned json
                            label: "A",
                            borderColor: "#3e95cd",
                            fill: false
                        }, {
                            data: datos.cot_values2,
                            label: "B",
                            borderColor: "#8e5ea2",
                            fill: false
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: data.name
                        },
                        animation: {
                            duration: 0, // general animation time
                        },
                        hover: {
                            animationDuration: 0, // duration of animations when hovering an item
                        },
                        responsiveAnimationDuration: 0, // animation duration after a resize
                    }
                });
                }
          
             });
       });
       });
  <select id="cur" name="cur">
    <option value="<?php echo $euro;?>">EURO</option>
    <option value="<?php echo $pound;?>">UK</option>
   
</select>
 <canvas id="myChart" width="800" height="450"></canvas>  

For more further verification here is the date format how it looks like: (when we call it after successful ajax call)

       alert(datos.cot_labels); 

enter image description here

Upvotes: 0

Views: 3148

Answers (1)

Mario L
Mario L

Reputation: 224

To take the value of variables you have to access the json obtained as an answer (data) and you have to convert "val1, val2, ..." in the vector [val1, val2, ...] with split:

var ctx = document.getElementById("myChart").getContext('2d');
        $.ajax({
            url: "server.php",
            type: "POST",
            data: {
                ...
            },
            success: function(data) {
                var datos = JSON.parse(data);
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: datos.cot_labels.split(','), ///in this way you access the data of the returned json
                        datasets: [{
                            data: datos.cot_values.split(','),///in this way you access the data of the returned json
                            label: "A",
                            borderColor: "#3e95cd",
                            fill: false
                        }, {
                            data: datos.cot_values2.split(','),
                            label: "B",
                            borderColor: "#8e5ea2",
                            fill: false
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: datos.name
                        },
                        animation: {
                            duration: 0, // general animation time
                        },
                        hover: {
                            animationDuration: 0, // duration of animations when hovering an item
                        },
                        responsiveAnimationDuration: 0, // animation duration after a resize
                    }
                });
            }
        });

Result:

Chart Line 1

Chart Line 2

Upvotes: 1

Related Questions