user3066341
user3066341

Reputation: 43

Google charts : date with json

I am using google charts and i have a problem to pass the date from php to javascript

I use this :

PHP :

$dataArray = array();
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC)) 
$thedate = "(".$year.", ".$month.")";
$fixe = "12";
$variable = "14";
$dataArray[] = array($thedate, (int) $fixe, (int) $variable);

JS :

var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Taux fixes');
data.addColumn('number', 'Taux variables');
data.addRows(<?php echo json_encode($dataArray); ?>);

The error is : Uncaught Error: Type mismatch. Value (2014, 1) does not match type date in column index 0

Does someone know how to send the date ? In which format ? Google charts want a "new Date(2012, 03)" in JS

Thanks.

Upvotes: 1

Views: 3311

Answers (1)

asgallant
asgallant

Reputation: 26340

When using JSON, the proper format for dates is a string like this: 'Date(year, month, day)' (note there is no new keyword used in the string), where month is zero-indexed (so January is 0 not 1). The only DataTable construction method that supports inputting dates in this fashion is passing a JSON representation of the DataTable directly to the constructor:

var data = new google.visualization.DataTable(<?php echo json_encode($dataTable, JSON_NUMERIC_CHECK); ?>);

This requires reconfiguring your PHP a bit to construct a proper DataTable JSON string. You need to create an associative array with 'cols' and 'rows' keys. The 'cols' key sets the columns for your DataTable, and the 'rows' key contains the rows of data:

$dataTable = array (
    'cols' => array (
        array('type' => 'date', 'label' => 'Date'),
        array('type' => 'number', 'label' => 'Taux fixes'),
        array('type' => 'number', 'label' => 'Taux variables')
    ),
    'rows' => array()
);
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC)) {
    // put results in $year, $month, $fixe, $variable

    $month = $month - 1; // correcting for javascript's 0-indexed months
    $dataTable['rows'][] = array('c' => array(
        array('v' => "Date($year, $month, 1)"),
        array('v' => $fixe),
        array('v' => $variable)
    ));
}

Upvotes: 3

Related Questions