2016-08-17 2 views
0

Всякий раз, когда я пытаюсь обновить таблицу через AJAX, нажав на кнопку, я получаю следующее сообщение об ошибке:this.canvas является недействительным в RGraph

TypeError: this.canvas is null 

this.context    = this.canvas.getContext('2d'); 

RGraph.bar.js (line 49, col 9) 

Я пробовал различные решения, но ничего не работает для меня. Вот мои два файла, которые используются в этом процессе:

index.php:

<?php 
include("includes/db-config.php"); 

$query = "SELECT * FROM `tb_daily_statistics`"; 
$rs = mysqli_query($con, $query); 

$labels = array(); 
$data = array(); 

while($row = mysqli_fetch_array($rs)) 
{ 
    $labels[] = $row['day']; 
    $data[] = $row['statistics']; 
} 

// Now you can aggregate all the data into one string 
$data_string = "[" . implode(", ", $data) . "]"; 
$labels_string = "['" . implode("', '", $labels) . "']"; 
?> 
<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>RGraph Charts</title> 
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> 
<script type="text/javascript" src="js/RGraph/RGraph.common.core.js"></script> 
<script type="text/javascript" src="js/RGraph/RGraph.bar.js"></script> 
<!--[if lt IE 9]><script src="js/RGraph/excanvas.js"></script><![endif]--> 
<script type="text/javascript"> 
$(document).ready(function(){ 

    var bar = new RGraph.Bar({ 
     id: 'mycanvas', 
     data: <?php echo $data_string; ?>, 
     options: { 
      labels: <?php echo $labels_string; ?>, 
      gutter: { 
       left: 50 
      } 
     } 
    }).draw() 

    $("#btnstats").click(function(){ 
     var order_by = $(this).data("order"); 
     //alert(order_by); 

     // Reset the canvas 
     RGraph.Reset(document.getElementById("mycanvas")); 

     // Prepare data to send over server 
     data = 'order_by='+order_by; 
     RGraph.AJAX.getJSON('ajax/update-chart.php?'+data, draw_graph); 
    }) 

}); 

// This is the AJAX callback function. It splits up the response, converts it to numbers and then creates the chart. 
function draw_graph(json) 
{ 
    // Set the JSON on the window object so that the button below can show it to the user. 
    //window.__json__ = json; 
    //$p(window.__json__); 

    // Reset the canvas 
    RGraph.Reset(document.getElementById("mycanvas")); 

    // Now draw the chart 
    var bar = new RGraph.Bar({ 
     id: 'mycanvas', 
     data: json.data, 
     options: { 
      labels: json.labels, 
      gutter: { 
       left: 50 
      } 
     } 
    }).draw() 
} 
</script> 
</head> 
<body> 

    <canvas id="mycanvas" width="600" height="250">[No canvas support]</canvas> 

    <br /> 

    <input type="button" id="btnstats" value="Order By Stats" data-order="statistics" /> 

</body> 
</html> 

обновление-chart.php:

<?php 
require_once '../includes/db-config.php'; 

/* 
echo "<pre>"; 
print_r($_GET); 
echo "<pre>"; 
*/ 

// Order by day 
if(isset($_GET['order_by']) && $_GET['order_by'] == "statistics") 
{ 
    $order_by = $_GET['order_by']; 

    $query = "SELECT * FROM `tb_daily_statistics` "; 
    $query .= "ORDER BY " . $order_by; 

    $rs = mysqli_query($con, $query); 

    $labels = array(); 
    $data = array(); 

    while($row = mysqli_fetch_array($rs)) 
    { 
     $labels[] = $row['day']; 
     $data[] = $row['statistics']; 
    } 

    // Now you can aggregate all the data into one string 
    $data_string = "[" . implode(", ", $data) . "]"; 
    $labels_string = "['" . implode("', '", $labels) . "']"; 

    echo json_encode(array('data' => $data_string, 'labels' => $labels_string)); 
} 
?> 

Ответ от сервера является хорошо. Вот что я получаю:

{"data":"[64, 75, 84, 94, 95, 98, 124]","labels":"['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon']" 
} 

В чем может быть проблема?

ответ

0

Ответ от сервера не отформатирован правильно, что понимает RGraph. Это

{"data":"[64, 75, 84, 94, 95, 98, 124]","labels":"['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon']" 
} 

Если вы

window.__json__ = json; 
$p(window.__json__); 

в вашей draw_graph функции (JSON), то ответ от сервера будет

Object { 
     data => [64, 75, 84, 94, 95, 98, 124] (string, 29) 
     labels => ['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon'] (string, 49) 
    } 

что неправильно. Скорее, это должно быть

Object { 
     data =>   Object { 
      0 => 64 (number) 
      1 => 75 (number) 
      2 => 84 (number) 
      3 => 94 (number) 
      4 => 95 (number) 
      5 => 98 (number) 
      6 => 124 (number) 
     } 
     labels =>   Object { 
      0 => Wed (string, 3) 
      1 => Fri (string, 3) 
      2 => Sun (string, 3) 
      3 => Thu (string, 3) 
      4 => Tue (string, 3) 
      5 => Sat (string, 3) 
      6 => Mon (string, 3) 
     } 
    } 

Чтобы устранить проблему, измените несколько строк кода в обновление-chart.php в

От

$data[] = $row['statistics']; 

в

$data[] = (int) $row['statistics']; 

Снимите следующие линии:

// Now you can aggregate all the data into one string 
$data_string = "[" . implode(", ", $data) . "]"; 
$labels_string = "['" . implode("', '", $labels) . "']"; 

От

echo json_encode(array('data ' => $data_string , 'labels' => $labels_string)); 

в

echo json_encode(array('data' => $data, 'labels' => $labels)); 
Смежные вопросы