Error set datetime in php when using jquery plot? - php

I have a sample code:
<?php
$dateset = array();
$data[] = array("2013-08-22", 1);
$data[] = array("2013-08-23", 5);
$data[] = array("2013-08-24", 3);
$dataset = json_encode($data);
?>
<div id="data"></div>
And javascript
<script>
var dataset = [];
dataset = <?php echo $dataset; ?>;
var data = [{
data: dataset,
}];
$.plot($('#data'), data, {
series: {
lines: {
show: true
},
points: {
show: true
}
},
xaxis: {
mode: 'time',
timeformat: '%d/%m/%y',
minTickSize: [1, 'day']
}
})
</script>
Result not show plot, how to fix it ?

You have array to string conversion. $dataset is an array and cannot print as a string.
dataset = <?php echo $dataset; ?>; // Notice: Array to string conversion
Try something like this:
<?php
$array_values = "";
foreach($dataset as $data){
if($array_values != ""){
$array_values .= ",";
}
$array_values .= $data;
}
?>
<script>
var dataset = [<?php echo $array_values; ?>];
</script>

Related

How can use SQL query to get values from DB in arrays for a line chart

I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}

this.map.tick is not a function

i am rendering data in a bar chart as a grouped data through php loops.
my data in js is as
var graphTarget12 = $("#myBarChartOdometer");
var barGraph = new Chart(graphTarget12, {
type: 'bar',
data: {
labels: 'Lahore,Ahmed',
datasets: [
{
label:'hi',
data:[320,100] },
{
label:'hi',
data:[120,200] },
]
}
});
My code in file is as follow
<script>
var graphTarget12 = $("#myBarChartOdometer");
var barGraph = new Chart(graphTarget12, {
type: 'bar',
data: {
<?php
$data = Odometer();
// echo count($data);
$name = array();
for($i=0;$i<count($data);$i++) {
$arrays = $data[$i];
array_push($name,$arrays['groupName']);
// print_r(count($meter));
// die;
$nameImplode = implode(',', $name);
}
?>
labels: <?php echo "'".$nameImplode."'"; ?>,
datasets: [
<?php
for($i=0;$i<count($data);$i++) {
$arrays = $data[$i];
$meter = $arrays['odometer'];
// print_r(count($meter));
// die;
$odoValue = array();
for($s=0;$s<count($meter);$s++)
{
$odo = $meter[$s];
array_push($odoValue,$odo['odometer']);
}
$implode = implode(',', $odoValue);
?>
{
label:'hi',
data:<?php echo "[".$implode."]";?>
},
<?php } ?>
]
}
});
</script>
My data format in php is as follow
$array = array(
array('groupName' => 'Lahore','odometer' => array(array('odometer' =>320),array('odometer' => 100))),
array('groupName' => 'Ahmed','odometer' => array(array('odometer' =>120),array('odometer' => 200)))
);
Please help me solve this.i spent 2days already and couldn't figure out solution.
if any other way please show me
Your label should be like array.
labels: ['Lahore','Ahmed'],
You've used like this
labels: 'Lahore,Ahmed',

Google visualization world map

I'm trying to retrieve results using json in order to display world map with country list.
This is what I got so far:
function drawRegionsMap() {
$.ajax({
url: 'getlist.php",
dataType: "json"
}).done(function(result) {
var data = google.visualization.arrayToDataTable(result);
var view = new google.visualization.DataView(data)
view.setColumns([0, 1])
var chart = new google.visualization.GeoChart(
document.getElementById('map'));
chart.draw(data, options);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
var options = {
width: "auto",
height: "auto",
colorAxis: {
colors: ['#E4B6D3', '#E06D94']
} // Map Colors
};
geochart.draw(data, options);
});
};
google.load('visualization', '1', {
'packages': ['geochart']
});
google.setOnLoadCallback(drawRegionsMap);
result returned from getlist.php is in json format:
{
"Country":[
"Germany",
"United States",
"Brazil",
"France",
"RU"
],
"Hits":[
200,
300,
400,
500,
600,
700
]
}
php code:
$data = array();
$data['Country'] = array();
$data['Hits'] = array();
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
for ($i = 0; $i < 6; $i++){
$data['Country'] = $country;
$data['Hits'] = $hits;
}
echo json_encode($data);
Looking in firebug console, I'm always getting : Error: Not an array
I've been trying to solve this puzzle for hours, but no success.
The returned result is an object, not an array.
The expected array would be:
[
["Country","Hits"],
["Germany",200],
["United States",300],
["Brazil",400],
["France",500],
["RU",600]
]
Modified PHP-code that returns this array:
<?php
$data = array(['Country','Hits']);
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
foreach ($country as $k => $v){
$data[] = array($v,$hits[$k]);
}
echo json_encode($data);
?>

Formatting json data to work in Flot

Is there anyway to convert this json data:
[
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
]
to like this:
{
"data": [[1999, 3.0], [2008, 0.9]]
}
Check type of values ("3.0" and 3.0, string and integer).
I am having hard time to figure this out, or is it even possible.
This is how I get the json data:
I have "data" table in my database where are "year" and "value" columns, I get them from database like:
$sql = mysql_query("SELECT * FROM data");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$encodedJson = json_encode($rows);
$encodedJson = json_encode($rows);
print $encodedJson;
I am trying to create a graph from my data, and json data must be formated properly to work in Flot.
All help is appreciated!
You could map your array of objects into an multidimensional array:
var mapped = originalData.map(function (obj) {
return [ parseInt(obj.year, 10), parseFloat(obj.value) ];
});
var newData = {
data: mapped
};
Possible solution
var a = [
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
];
var b = [];
$.each(a, function(_index, _item){
var c = [_item["year"], _item["value"]];
b.push(c);
});
console.log(b)
try this.
PHP:
$sql = mysql_query("SELECT * FROM data");
$rows = $sql->results_array();
$return_args = array();
foreach($rows as $row){
$tmp[0] = $row['year'];
$tmp[1] = $row['value'];
array_push($return_args,$tmp);
}
$encodedJson = json_encode($return_args);
print $encodedJson;

json_encode in php

i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"
{"valor":"20"},{"valor":"50"}
i need
{"valor1":"20"},{"valor2":"50"}
the script
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while($row = mysql_fetch_assoc($query)) {
$arr[] = $row;
}
echo json_encode($arr);
in ajax
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery.ajax({
url: "chart.php",
dataType: "json",
success: function(json){
var msg = "Nome: " + json.valor1+ "\n";
msg += "Sobrenome: " + json.valor2 + "\n";
alert(msg);
}
});
});
});
</script>
the problem is: I need to create a loop that create uniques names, as value1, value2, value3
like
$arr['valor1'] = "Evandro";
i tried a loop- for, but i get an error of memory
thanks
Try this:
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array("valor{$i}" => $row["valor"]);
++$i;
}
echo json_encode($arr);
Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:
$arr["valor{$i}"] = $row["valor"];
$index = 1;
while($row = mysql_fetch_assoc($query)) {
$key = 'valor'.index;
$arr[$key] = $row;
$index++;
}
Does that give you a memory error? It shouldn't.

Categories