I'm trying to print out an array of dates pulled from an API, which come out formatted as YYYYmmdd, i.e. 20160701. When I convert them to a friendlier format and then go to print them in Highcharts, it actually will do a mathematical calculation based on the operator being used to separate the date elements. Obviously that's not what I want it to do. So the first date is actually performing 7 minus 1 minus 2016, resulting in the -2010. Does anyone know what is causing this?
PHP Snippet
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('m-d- Y');
}
Javascript Highchart Plugin
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo implode(',', $dates);
?>
]
},
What the dates end up looking like:
The problem is that you're not injecting any quotes in the Javascript source.
What you get is something like:
$('#myChart').highcharts({
xAxis: {
categories: [ 7-1-2016 ] // <--- should be [ "7-1-2016" ]
}
});
which is evaluated as categories: [ -2010 ] on the Javascript side.
You should do:
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo '"'.implode('","', $dates).'"';
?>
]
}
});
Or if you prefer to have this fixed in the PHP code that is building this array:
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('"m-d-Y"');
}
EDIT: as suggested by jlbriggs, a better approach would be to use json_encode().
At least on $dates ...
$('#myChart').highcharts({
xAxis: {
categories: <?php echo json_encode($dates); ?>
}
});
... or on the whole object passed to highcharts() (assuming it's entirely built on the PHP side):
$('#myChart').highcharts(<?php echo json_encode($highChartsObject); ?>);
Related
I have a jQuery function to print charts (jqPlot framework).
I want to print several charts with different options. So I need to call this function more than once and with different values.
I have an ugly solution like this:
//----- index.php:
// chart 1
$values = "[1,2,3]";
$id_chart = "chart1";
$options = "{...}";
include 'chart.php';
// chart 2
$values = "[8,2,5]";
$id_chart = "chart2";
$options = "{...}";
include 'chart.php';
//---- chart.php
<script>
$(function () {
$.jqplot(<?php echo $id_chart;?>, <?php echo $values;?>, <?php echo $options;?>);
});
</script>
I tried another solution - call javascript function with variables and invocate jQuery function in JS function.
//---- index.php:
<script>
function printChart(opt1,opt2,opt3){
$(function () {
$.jqplot(opt1, opt2, opt3);
});
}
</script>
<?php
// chart 1
$values = "[1,2,3]";
$id_chart = "chart1";
$options = "{...}";
echo "<script>
printChart(\"$id_chart\",\"$values\",\"$otpions\");
</script>";
// chart 2
$values = "[8,2,5]";
$id_chart = "chart2";
$options = "{...}";
echo "<script>
printChart(\"$id_chart\",\"$values\",\"$otpions\");
</script>";
?>
But off course, jQuery can not 'see' variables from JS. Is it possible to pass the variables from JS to jQuery?
Do you have, please, any other suggestions for an optimal solution?
Thank you guys.
What you need to understand is that PHP is a server side language and JavaScript is a client side language. The PHP will completely execute, generating an HTML page (containing JavaScript) and then send that to the client's browser. The browser renders the HTML and executes the JavaScript. So what you need to do is print the information for JavaScript to the page. This should suffice:
<?php // your PHP to generate the values into an array
$charts = [
[
'values' => [1,2,3]
'id_chart' => 'chart1',
'options' => '{...}'
],
[
'values' => [4,5,6]
'id_chart' => 'chart2',
'options' => '{...}'
]
];
?>
<script>
var charts = JSON.parse(<?= json_encode($charts) ?>);
$.each(charts, function () {
$.jqplot(this.id_chart, this.values, this.options)
});
</script>
Is it possible to pass the variables from JS to jQuery?
jQuery is a library for javascript.
this means that jQuery variables are javascript variables.
which means you can use them like any other javascript variables.
In database table I have age column in which have more than 50 rows.
id age
1 45
2 41
3 09
......
60 11
I always have 10 keys in array ,
<?php
$arr = array(0,0,0,0,0,0,0,0,0);
echo json_encode($arr)."<br>";
$con = mysqli_connect('127.0.0.1','app_user2','qwe123','test');
$select="select age from ad;";
$res = mysqli_query($con, $select);
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
echo json_encode($arr)."<br>";
}
?>
I'm getting following output=>
[0,0,0,0,0,0,0,0,0,[0,45]]
[0,0,0,0,0,0,0,0,[0,45],[1,41]]
[0,0,0,0,0,0,0,[0,45],[1,41],[2,11]]
[0,0,0,0,0,0,[0,45],[1,41],[2,11],[3,21]]
[0,0,0,0,0,[0,45],[1,41],[2,11],[3,21],[4,44]]
.............................
[[1,41],[2,11],[3,21],[4,44],[5,13],[6,15],[7,12],[8,7],[9,14],[10,11]]
........................
Now when i execute
echo json_encode($arr)
in JavaScript i'm getting only last 10 values. i want to execute all the rows one by one. how can i do that? Is it possible?please help.
here is my script code
<script type="text/javascript">
var data=[];
data=<?php echo json_encode($arr); ?>;
document.write(data);
</script>
That's because your string isn't in a valid json format. Then you get output of just one line. You may consider build in a correct way like:
$myArray = []
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
array_push($myArray, $arr);
}
then:
data=<?php echo json_encode($myArray ); ?>;
(PS.: hardcode server side code in javascript isn't a good practice)
On each run through the loop, you assign $arr using array_slice and assign 9 elements to it (starting from element 1, length 9). Later in the loop iteration, you add a new element to the end of the array with a $arr[] = ... assignment.
Since you are assigning the array to have 9 elements and then adding 1 element on each iteration, it will always end up being 10 elements long at most, and no more.
I have the following php code that gives an array variable called "markers".
window.markers = [];
<?php if( have_rows('actin_center') ): ?>
<?php while( have_rows('actin_center') ): the_row(); ?>
window.markers.push( [ ['<?php the_sub_field('center_name'); ?>', '<?php the_sub_field('center_address'); ?>', <?php the_sub_field('latitude'); ?>, <?php the_sub_field('longitude'); ?>] ] );
<?php endwhile; ?>
<?php endif; ?>
This works fine so far yet returns the array (on alert) as:
Cool center 1,Rewitz Gofella, 1234 Lorem,50,50,Cool center 2,Lorem Ipsum, 1234 Quosque,60,60,Cool center 3,Veniat elaborat, 1234 Ipsum,70,70
What I need, yet, is the following form keeping the arrays (of sub_fields) as they originally are inside the array and NOT concatenate them. As:
var markers = [
['First Center','First Address',50,50],
['Second Center','Second Address', -25.363882,131.044922],
['Third Center','Third Address', 10.363882,95],
['Fourth Center','Fourth Address', -50,-90],
['Fifth Center','Fifth Address', 30,5],
];
As you can see in the code above I tried with the simple double bracket [[ ]] but this doesn’t work.
How is this to be done correctly?
Thanks so much for help.
PS:
If someone feels urged to down vote my question, please be so kind to let me know why so I may learn something.
Due to comments:
alert( [[1,2][3,4]] ) will popup wrong 1,2,3,4
alert( JSON.stringify([[1,2][3,4]]) will popup [[1,2],[3,4]]
.push([1,2]) will add an array to markers: [[1,2],[3,4],[5,6]]
.push(1,2) will add elements to markers: [1,2,3,4,5,6]
But better way, is don't execute javascript .push (save client CPU time)
Define array in javascript in this way:
window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];
result should looks like this
window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];
The code I am using is below.
I want to make a simple graph based on the data from my database table.
It is working now but I want date on the bottom axis is not appearing properly.
while the value of variable is
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
that is right. But I cant get this date on the x-axis. any solution there?
The way I am getting getting this value is
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Then I pass this data in java script like this:
var graphData = [{
data: [ <?php echo $str; ?>]
}
];
But At the end I can not get the date on x axis.
PS:
I am working on the view of codeigniter application.
Have a look at the documentation for time series data.
You need javascript timestamps. In PHP you get them simply with
strtotime($usd[$i]["transaction_date"]) * 1000
Then your data should look like this:
[1427238000000, 1236], [1427324400000, 3000], ...
For the labels on the x axis, use the timeformat options to get back the format you want:
xaxis: {
mode: "time",
timeformat: "%d-%m-%y"
}
I would like to replicate this highcharts column graph: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/
I'm pulling my data from a table and it looks like this.
I want the Job_Num on the x-axis where brands are in the fiddle, PercentofBudgetedHrs would be the brandsData. Now when you click a job number, it drills down to departments and shows their percentage of budgeted hrs.
I have the first part working, but I'm using different code like so: http://jsfiddle.net/98Fuq/4/
Here is what I changed in that code:
$sql = "SELECT * FROM view_percentof_budgeted WHERE PercentofBudgetedHrs < 1000 && PercentofBudgetedHrs IS NOT NULL";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result)) {
$jobNum[] = $row['Job_Num'];
$jobData[$row['Job_Num']] = $row['PercentofBudgetedHrs'];
$jobDrillData[$row['Job_Num']][] = $row;
}
The part I changed in the JS:
var colors = Highcharts.getOptions().colors,
categories = [<?php echo join($jobNum, ',') ?>],
name = '% of budgeted hours',
level = 0,
data = [
<?php echo join($jobData, ',') ?>,
];
function setChart(name, categories, data, color, level) {
chart.xAxis[0].setCategories(categories);
chart.series[0].remove();
chart.addSeries({
name: name,
data: data,
level: level,
color: color || 'red'
});
}
How do I go about doing it the way that first fiddle I posted does it? I like my method of pulling the data from a table so I don't want to use a tsv, I'm just confused on the drilldown part. I've looked at examples but can't seem to figure it out.
Instaed of using join() I advice to prepare correct strucutre of arrays in php, then use json_encode() including JSON_NUMERIC_CHECK flag. As a result you can get this json by $.getJSON and put in highcharts.