jQuery issue with PHP data and Highcharts - php

I'm having an issue with the X axis data which is dynamic as it seems to use all the values in the first column.
I'm doing the below:
<div id="season_data_block" style="display: none;">
<?php
foreach($champ_name as $champ_id => $stat_value) {
foreach ($stat_value as $cn => $cs) {
if($champ_id != 0) {
echo '"'.$cn.'",';
}
}
}
?>
</div>
This is putting the PHP data into a hidden div. Then I am using jQuery to access the text from that div.
<script type="text/javascript">
$(document).ready(function(){
var chart_data = $("#season_data_block").text();
$('#stats_chart').highcharts({
chart: {
type: 'column',
backgroundColor: "#F5F5F5",
},
title: {
text: ' '
},
xAxis: {
categories: [chart_data]
},
The issue I'm having is that when the data is inserted into the javascript xAxis, it shows all the php data on the first xAxis value then the rest is defaulted, like below.
First: "name 1","name 2","name 3",
Second: 2
Third: 3
Fourth 4
I want it to be
First: "name 1"
Second: "name 2"
Third: "name 3"
etc. Why is it doing that?
Thanks

Fixed it. I turned my PHP data into another array and then json_encode() that array into a javascript array. Simple :)

Related

Getting Data from PHP, JSON Highcharts?

Hi I am trying to get data from MySql table and show the data in Highcharts by using PHP and Json
I have try the example from internet and it is working fine but when I try to get data from my file it show nothing.
What I am trying to do:
I am creating table of office attendance system and trying to show record day by day. So at y axis I want to count names of employees and x axis the date of attendance.
Problem: Nothing Is show from mu json.
Here is what my Json looks like:
[["Hamza","07\/04\/2014"],
["Junaid","07\/04\/2014"],
["Usman","07\/04\/2014"],
["Rajab","07\/04\/2014"],
["Hamza","08\/04\/2014"],
["Junaid","08\/04\/2014"],
["Usman","08\/04\/2014"],
["Rajab","08\/04\/2014"]]
I am having to value names and dates.
My PHP which is creating my Json code:
// Set the JSON header
header("Content-type: text/json");
$result = mysqli_query($con,"SELECT * FROM attendence");
$a=array();
while($row = mysqli_fetch_array($result)) {
$row['name'] . "\t" . $row['date']. "\n";
$b=array();
array_push($b,$row['name']);
array_push($b,$row['date']);
array_push($a,$b);
}
echo json_encode($a);
and this is my Jquery code:
$(function() {
$.getJSON('highchart.php', function(data) {
// Create the chart
$('#chart').highcharts('StockChart', {
rangeSelector : {
selected : 1,
inputEnabled: $('#chart').width() > 480
},
title : {
text : 'Attendence'
},
series : [{
name : 'Empolyees',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
In the json_encode() you need to use JSON_NUMERIC_CHECK flag to avoid use string in your JSON
In the highstock you need to have timestamps and value, not name and date.
Dates should be timestamp, and as first element in array, not second as you have.
If you want to get a count of all people on a given day, you need to write a SQL query that returns that information. Assuming that date field is a datetime type and name is of varchar type:
SELECT COUNT(name) FROM attendence GROUP BY DATE(date);
perhaps you need to define what kind of data your x-axis will have
take a look at this fiddle (taken from highcharts website)
$(function () {
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
data: [
[Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
}]
});
});

How to create a chart-js pie chart with PHP data variables?

I am creating a pie chart using chart.js; however, the value I want in the pie chart is a PHP variable. How do I add it to the pie chart? Currently I have this for the data for the pie chart:
var pieData = [
{
value: 40,
color:"green"
},
{
value : 40,
color : "red"
}
];
However, I need to replace the two 40s with PHP variables.
You can use PHP echo function for this. You can concatenate your PHP variables into the echo statement. Note: If you want to send an array to the JS, just use json_encode() like shown below.
PHP section:
<?php
echo '
<script type="text/javascript">
var v1=40;
var c1="green";
var v2=40;
var c2="red";
var jsArray =' . json_encode($phpArray) . '; // Remove this if not needed...
</script>';
?>
Javascript section:
var pieData = [
{
value: v1,
color: c1
},
{
value : v2,
color : c2
}
];
You can wrap everything in a function for cleaner code. Hope it helps.

Get value with php and mysql in var name[value1,value2,value2]

How I can insert array value in php and mysql from variable Var s1, s2, s3:
$(function () {
var s1 = [100, 200, 300]; //How to Get Value from mysql database
var s2 = [30, 80, 90]; //How to Get Value from mysql database
var s3 = [120, 90, 80]; //How to Get Value from mysql database
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['2010', '2011', '2012'];
var plot1 = $.jqplot('chart3', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
shadow: true, // show shadow or not.
renderer: $.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true
}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{label: 'Hotel'},
{label: 'Event Regristration'},
{label: 'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {
formatString: '$%d'
}
}
},
grid: {
borderColor: '#000', // CSS color spec for border around grid.
borderWidth: 2.0, // pixel width of border around grid.
shadow: true // draw a shadow for grid.
}
});
// Bind a listener to the "jqplotDataClick" event. Here, simply change
// the text of the info3 element to show what series and ponit were
// clicked along with the data for that point.
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
});
});
2 ways:
Ajax
Use: $.getJSON ( http://api.jquery.com/jQuery.getJSON/ )
var ses = {};
$.getJSON('page_adress.php', {variable_you_want_to_pass1: 'its value', variable_you_want_to_pass2: 'var 2 value'}, function(data) {
ses = data;
});
In your PHP:
<?php
$passed_var_1 = $_REQUEST['variable_you_want_to_pass1'];
//.... etc
//Here you get your data from mysql, cast it into array
header('Content-type: application/json');
echo json_encode($dbdata);
?>
So basically after request finishes you will have exact array you had in PHP transferred in JavaScript. Have in mind that this technique uses AJAX. If you want to avoid that, you will have to use second technique.
Dynamically Creating JS
Make PHP generate your javascript. In this case you would have in your main page
<script src="js_data.js.php" type="text/javascript"></script>
In your js_data.js.php file:
<?php
header("content-type: application/x-javascript");
$s1 = array(100,200,300);
//....
var s1 = [<?=implode(', ', $s1)?>],
s2 = [<?=implode(', ', $s2)?>],
s3 = [<?=implode(', ', $s3)?>];
?>
First method (w/o ajax & json)(untidy-way)
First fetch the value from database and have it in PHP variable.
Then put html element in page and assign the value to it.
Then use it in javascript using document.getElement method.
// assume that you have got value from database in $valueFrmDB.
$valueFrmDB;
Now, take html element(you might have to take more than one)
<input type="hidden" id="something" name="something" value="echo value of $valueFrmDB here" />;
Then, in javascript
var vfd = document.getElementById('something').value;
convert string to array
Second method(with ajax and json)(simple & correct but must know ajax and json)
Use ajax to fetch the values from database
Then use json to pass that values to javascript
simply you can do this by:
<?php
$query = mysql_query("SELECT * FROM attendence");
$results = array(array());
while($line = mysql_fetch_array($query)){
$results[] = $line;
}
?>
Javascript
<script type="text/javascript">
$(document).ready(function(){
var data = <?php echo json_encode($results); ?>; //array uses here
var plot1 = jQuery.jqplot ('chart1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true}
},
legend: { show:true, location: 'e' }
});
});
</script>

issue with autocomplete

I'm coding a new website to learn PHP, and coding, and am making an autosuggest that is populated by two mysql tables.
Heres my code (Yes, I'm using mysql, but I'll rewrite this in mysqli once I find a solution!):
suggest.php:
require("./config.php");
$q = $_GET['q'];
$names = '';
$result = mysql_query("SELECT name FROM company WHERE name LIKE '$q%' UNION SELECT cat FROM cat WHERE cat LIKE '$q%' UNION SELECT subcat FROM subcat WHERE subcat LIKE '$q%' LIMIT 10"");
while ($row = mysql_fetch_array($result)) { $names .= $row[name]."\n"; }
echo $names;
?>
index.php ( where the searchbox is)
<form class="form-search span8 offset6">
<input type="text" id='search' name='q' class="input-medium search-query">
<button type="submit" class="btn btn-warning">GO!</button>
</form>
later in index.php (I call jquery.js before):
<script src="public/js/jquery-ui-1.8.22.custom.min.js" type="text/javascript"
charset="utf-8"></script>
<script>
$(function () {
$(document).ready(function () {
$("#search").autocomplete("./suggest.php");
});
});
</script>
The rows I'm trying to populate my autosuggest are the subcat row from the subcat table, the name table from company table, and cat from cat table.
The autosuggest isn't showing up? What's wrong?
Thanks for all help!
Try sending JSON formatted data from php, like:
$names = array();
while ($row = mysql_fetch_array($result)) {
$names[] = $row['name'];
}
echo json_encode($names);//format the array into json data
http://jqueryui.com/demos/autocomplete/
Expected data format The data from local data, a url or a callback can
come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
you are just returning the names selected separated by line breaks
read the documentation of jquery ui autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The
value will be inserted into the input element after the user selected
something from the menu. If just one property is specified, it will be
used for both, eg. if you provide only value-properties, the value
will also be used as the label.
from the documentations of jquery autocomplete
http://jqueryui.com/demos/autocomplete/
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
try to pass your data accordingly.

javascript slideshow array

I'm using slideshow 2 (http://www.electricprism.com/aeron/slideshow/) to show a couple of pictures on my website, the problem is number of images and their locations should be hard coded into the javascript code.
i want to use an array (from a php file output)
and somehow assign new values to the "var data" so that all of my images in the folder will be shown without the need to manually update each time.
any ideas?
<script>
window.addEvent('domready', function(){
var data = { '5.jpg': { caption: '1' }, '2.jpg': { caption: '2' }, '3.jpg': { caption: '3' }, '4.jpg': { caption: '4' }};
new Slideshow('overlap', data, { captions: { delay: 1000 }, delay: 3000, height: 300, hu: 'images/', width: 400 });
});
</script>
if you use PHP then you can easily do this.
say, you have logic that gets all your files into an array that looks like this:
$foo = Array("2.jpg" => "2", "3.jpg" => "3");
representing the filename and the caption
you can then do:
<?php echo json_encode($foo); ?>
to output it.
if you were to output it inside a js block into a variable:
var data = <?php echo json_encode($foo); ?>;
wich should actually render as:
var data = [{"2.jpg": "2"},{"3.jpg": "3"}];
Also, keep in mind in your example, you don't actually use an array, you use an Object. There's a substantial difference. In the output I suggest you will get an Array of Objects. You'd loop it like so:
Array.each(data, function(img) {
});
but because your keys are dynamic, it makes for difficult iteration, you need to Object.each or Object.keys or for (var key in obj) {} to get the properties. A better data structure would be:
$foo = Array(Array("name" => "2.jpg", "caption" => "two"), Array("name" => "3.jpg", "caption" => "three"));
which means in your js loop, you can reference:
Array.each(data, function(img) {
img.name; // filename
img.caption; // title
});

Categories