I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js. I've tried echoing the JSON from the controller and it gets the necessary values.
In my PHP file, there is an ajax call that gets data using a function in the controller.
$.ajax({
url: "index.php/Sales/topClients",
method: "GET",
success: function(data){
var parsedData = JSON.parse(data);
console.log(parsedData[0].Name);
var clientname = [];
var orqty = [];
for(var i in parsedData){
clientname.push(parsedData[i].Name);
orqty.push(parsedData[i].Quantity);
}
var chartdata= {
labels: clientname,
datasets:[
{
label: 'Ordered Quantity',
backgroundColor: [
'rgba(231, 76, 60,0.7)',
'rgba(52, 152, 219,0.7)',
'rgba(46, 204, 113,0.7)',
'rgba(230, 126, 34,0.7)',
'rgba(155, 89, 182,0.7)',
],
borderColor: [
'rgba(231, 76, 60,1.0)',
'rgba(52, 152, 219,1.0)',
'rgba(46, 204, 113,1.0)',
'rgba(230, 126, 34,1.0)',
'rgba(155, 89, 182,1.0)',
],
borderWidth: 1,
data: orqty
}
]
};
Chart.defaults.scale.ticks.beginAtZero=true;
Chart.defaults.global.title.display= true;
var ctx= $("#RMCanvas");
var barGraph= new Chart(ctx,{
type: 'bar',
data: chartdata
});
},
error: function(data){
console.log(data);
}
});
This is the controller (Inventory)
public function topGoods(){
$top5fgsold= $this -> Inventory_Model -> getTopGoods();
echo json_encode($top5fgsold);
//$this->load->view("SA_Home-Latest");
}
This is the model: Inventory_Model
<?php date_default_timezone_set('Asia/Manila');
class Sales_Model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function getTopClients(){
$this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
$this->db -> from("salesinvoicedetails");
$this->db -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
$this->db -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
$this->db -> where("salesinvoice.Status", 2);
$this->db -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
$this->db -> where("OrderDate <= NOW()");
$this->db ->group_by("1");
$this->db ->order_by("q", "desc");
$this->db ->limit(5);
$topclientresult= $this-> db -> get();
return $topclientresult-> result_array();
}
}
?>