marie_dev
marie_dev

Reputation: 25

Morris Chart refresh issue with php data

I'm struggling with Morris charts for some time now, I would like to update my Morris chart onclick button event with php data. I start by loading data like below, I include first my php page, but nothing happen when I try to load new data on click :(

<?php include ('loadchart.php');?>

var graph =  new Morris.Area({
  element: 'morris_area',
                  xkey: 'x',
                ykeys: ['y', 'z'],
                 lineColors: ['#5969ff', '#ff407b'],
                   resize: true,
                   gridTextSize: '14px'
});
graph.setData([<?php echo $data; ?>]);
graph.redraw();

Until then all is well :D but when I try to load the below php data nothing happen :

"{x:'2018-03-20',y:1,z:7}, {x:'2018-03-22',y:31,z:5}, {x:'2018-03-25',y:7,z:21}"

generated like below

<?php
$uname = $_POST["type1"];

if ($uname=='search1')
{   
$var1= '2018-03-20';
$var2= 1;
$var3= 7;
$chart_data1 = '';
$chart_data1 .= "{x:'".$var1."',y:".$var2.",z:".$var3."}, ";
$var11= '2018-03-22';
$var22= 31;
$var33= 5;
$chart_data1 .= "{x:'".$var11."',y:".$var22.",z:".$var33."}, ";
$var111= '2018-03-25';
$var222= 7;
$var333= 21;
$chart_data1 .= "{x:'".$var111."',y:".$var222.",z:".$var333."}, ";
$chart_data1 = substr($chart_data1, 0, -2); 
echo json_encode($chart_data1);
}
?>

my AJAX code :

function Onclickbutton()
{
$.ajax({
    type: "POST",
    url: 'admin/Mynewdata.php',
    data: {type1: 'search1'},
    success: function(data){
 alert(data);
 graph.setData(data);
graph.redraw();
        }
});

}

Any help would be appreciative :)

Upvotes: 2

Views: 151

Answers (2)

marie_dev
marie_dev

Reputation: 25

I found a workaround :D, I create an new array in my js code , thank you for you help

function LoadResultMorris()
{
$.ajax({
    type: "POST",
    url: 'admin/data.php',
    data: {type1: 'search1'},
    success: function(data){
var array1 = [];
var i=0;
$.each(JSON.parse(data), function(key,obj) {
    array1[i] = {};
    array1[i]['x']=obj.x;
     array1[i]['y']=obj.y;
     array1[i]['z']=obj.z; 
     i++;
});
graph.setData(JSON.stringify(array1));
graph.redraw();
        }
});

}

Upvotes: 0

cOle2
cOle2

Reputation: 4784

I think the crux of your issue is that the JSON you are manually creating is not valid.

Try creating an array of your values before passing that array to json_encode:

$arr= array();
$arr[] = array('x'=>'2018-03-20', 'y'=>1, 'z'=>7);
$arr[] = array('x'=>'2018-03-22', 'y'=>31, 'z'=>5);
$arr[] = array('x'=>'2018-03-25', 'y'=>7, 'z'=>21);

echo json_encode($arr);

Upvotes: 1

Related Questions