highcharts dynamic data from php - php

I am trying to plot a chart (Spline) using data that is dynamically generated from PHP. The JavaScript library I am using for this purpose is HighCharts.
The PHP generates an array of values in the format like
array(
array("1304294461000",69,"1304899261000",28),
array("1304294431000",3,"1304899161000",32)
)
which I am then passing onto a javascript array using json_encode. However, when I push these values as data, it doesn't seem to be working.
For example, here's an example with relevant code snippets like -
var namesArr = <?php echo json_encode($namesArr); ?>;
var progressTrendsData = <?php echo json_encode($progressTrendsData); ?>;
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
for(var i=0;i<namesArr.length;i++) {
options.series.push({
name: namesArr[i],
data: progressTrendsData[i]
});
}
chart = new Highcharts.Chart(options);
The options contain other relevant data needed for the chart of course.
However, the only thing the above code is doing is plotting a single value at the date January 1 irrespective of the actual data that is being pushed.

I would tend to agree w/Mark on this. It is hard to tell exactly your data is supposed to end up looking like though. Try looking at the data loading portion of the ajax data example on the highcharts demo page.
UPDATE:
Try the following pseudocode:
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
var seriesInfo=[];
seriesInfo[0]={"name":"Series A","data":[]};
seriesInfo[1]={"name":"Series B","data":[]};
//Loop over the series and populate the data
seriesInfo[0].data.push({x:<insert Series A timestamp>,y:<insert Series A y value>});
seriesInfo[1].data.push({x:<insert Series B timestamp>,y:<insert Series B y value>});
options.series.push(seriesInfo[0]);
options.series.push(seriesInfo[1]);
chart = new Highcharts.Chart(options);

Related

ChartJSPlugins Issue

`<script>
Chart.pluginService.register({
beforeDraw: function (chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.config.options.elements.center.text,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
// chart1
var data = {
labels: ["Red", "Blue"],
datasets: [{
data: [50],
backgroundColor: ["#BEFF60", "#36A2EB"],
hoverBackgroundColor: ["#BEFF60", "#36A2EB"]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
type: 'doughnut',
data: data,
options: {
title: {
display: true,
text: 'OEE Chart'
},
elements: {
center: {
text: parseInt(<?php echo json_encode($OEE); ?>) + '%', //set as you wish
}
},
cutout Percentage: 85,
legend: {
display: false
}
}
});
</script>
`
I have few questions here.
I have already created Plugins Service and doughnut chart code where I standardize everything including having a text in between the doughnut chart - how can I small changes the Plugin Service so that where I can add picture send towards backwards and bring the text infront?? - Is it possible this same Plugin Service used after modification answers given by anyone where for other charts but dont want to add the picture and text as other charts will be either bar graph or line chart etc... can anyone guide me with these kind of things. I'm not sure how to do it.. any advice??
If lets say I want to do chartsJS for stepped line chart how is that?? I tried using the same Plugin Service but failed. if if each type of chart need to use different plugins I can do it... but the issue I will create their separate files and call them in PHP index folder (as the main file running the website but when I add the JavaScript link and add call the name from the JS file into the PHP index file failed. Hopefully someone can guide me or advice me on this
when i use the same PluginService(which is used for doughnut chart) i cannot show the results for barchart , line chart etc using the same PluginService when i pass <php json() file ?> from the database file i created to pass the data into data[] in chartJS
-dscsccsss\\\\\\

Pass data from jQuery to PHP file in one set

I have a table and some <td> have a data, but not all of them. On a button click I run jQuery function which checks each <td> and where the data is present, grabs the data.
After that the data is being passed to php file and inserted into my DB. Everything works great.
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
$.post({ url: "insert_data.php", data: {worker:worker, quarter:quarter, station:station, type:type} });
});
}
else { return false; }
}
I am wondering if instead of calling the php with ajax for every <td>, maybe there is a way to pass the data like one package? I checked at least couple dozen different articles here and on other websites and it seems that very often JSON is used for that purpose.
I've never worked with JSON and after several days of trying different approaches, still can't figure out what I am doing wrong. I will appreciate any help.
All I need is to pass data from my table into php file (and unpack it in there). I do not need to display it simultaneously on the html page.
Here is one of the versions which doesn't work:
JS:
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
var myArray = []; // var to store all records for json data transfer
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
var record = {worker:worker, quarter:quarter, station:station, type:type}; // sd - short for schedule data
myArray.push(record); // add every record to same array
});
console.log(myArray);
$.post({ url: "insert_data.php", data: {myArray: myArray }, success: function(data){ alert('Items added'); }, error: function(e){ console.log(e.message); } });
}
else { return false; }
}
In console I see following data (it looks like the data is being added to the array without issues):
(4) [{...}, {...}, {...}, {...}]
0: {worker: "556", quarter: "1", station: "abc_15", type: "rework"}
1: {worker: "147", quarter: "2", station: "abc_37", type: "rework"}
2: {worker: "345", quarter: "3", station: "abc_15", type: "rework"}
3: {worker: "12", quarter: "4", station: "abc_15", type: "rework"}
PHP:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
var_dump($mySchedule);
foreach ($mySchedule as $sched) {
$worker = $sched['worker']; // or: $sched->worker; - doesn't change the result
$quarter = $sched['quarter'];
$station = $sched['station'];
$type = $sched['type'];
// code to insert data into my DB - works fine when I pass data one by one instead of array
}
HTML:
I also added this script to the page with my table:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-json/2.6.0/jquery.json.min.js"></script>
I am not sure if it is needed or not.
--
It feels that the problem is in the way how I "unpack" the array. But I am not sure... I tried to follow all advises I could find here, but maybe I just miss something really important.
I tried:
$mySchedule[] = json_decode($_POST["myArray"]); // in insert_data.php
data: { json: JSON.stringify(myArray) } // in jQuery function
and some other advises...
update
I got some help from one of my colleges. So, the jQuery code stayed without changes. PHP code had couple minor changes and it works fine now. The changes in PHP:
$mySchedule = $_POST["myArray"]; // get the json array
instead of:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
That is it. Thank you very much for help and advises. I hope this example will be helpful to others.

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>

Using php, ajax and jqplot to make a pie chart

I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.

Build json to send to php using a for loop (maybe)

I've googled around, but i can find a way to build json with jQuery and send it to php using a for loop. I have a html table, and i want to take values from each row (i dont know how many rows/values there will be) construct a json string, ie. [{"row": 1, "supp_short_code" : blah blah....}, {"row": 2, ....} ....]
but i dont know how to keep adding to the json datastring each time jQuery finds more values if that makes sense??
EDIT:
So if i have this
$('#submit').live('click',function(){
var supp_short_code=$('.supp_short_code').text();
var project_ref=$('.project_ref').text();
var om_part_no=$('.om_part_no').text();
var description=$('.description').text();
var cost_of_items=$('.cost_of_items').text();
var cost_total=$('.cost_total').text();
var dataString = 'string=//' + supp_short_code + '//' + project_ref + '//' + om_part_no + '//' + description + '//' + cost_of_items + '//' + cost_total
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function()
{
alert("Order Submitted");
}
});
});
So what (roughly) would i need to change in this code?
Ok, so as you can see by the screenshot, i'm using jquery to dynamically add the bottom table when a user click a row from the top table, its calculating totals and they can specify which supplier they want to use. I'm then using jquery to grab these values into the $('submit') bit of jquery code at the top. I then want to send these values to a php page that will somehow parse the received data at insert it into a mysql db, as something like "id 1 product blah price blah supplier blah total cost £x, id 2 product blah2 price blah2 supplier blah total cost £x" so some fields, ie the total cost and supplier will be the same, but the php might be receiving 3 different products for the same order if that makes sense? Thanks!
You don't need to build the json, just build the data array and send it with .post, .get or .ajax. jQuery will take care of encoding the array for you:
var data = {};
for (var i = 0; i < 3; ++i) {
data['field' + i] = 'value' + i;
}
$.post ('http://mysite.com/page', data, function() { alert('succes!'); });
Your server-side code's $_POST array will containing:
array( 'field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3');
For your example, I would reconsider sending the data as a string and instead send the data as well-formated key/value pairs. Your server-side code can more easily decide what to do with it, and your JS won't require a rewrite if the server-side code needs the string to be built differently.
$.ajax ({
type: "POST",
url: "order.php",
data: {
supp_short_code: $('.supp_short_code').text(),
project_ref: $('.project_ref').text(),
om_part_no: $('.om_part_no').text(),
description: $('.description').text(),
cost_of_items: $('.cost_of_items').text(),
cost_total: $('.cost_total').text()
}
//...
});
Update
You could reduce the amount of typing by throwing your field names into an array, and appending the class name of any fields you want to include in the data array. Then loop over each of your table rows and extract the values:
var fields = [ 'supp_short_code', 'project_ref', 'om_part_no',
'description', 'cost_of_items', 'cost_total'];
var data = [];
// loop over each row
$('#my-table tr').each(function (i, tr) {
// extract the fields from this row
var row = {};
for (var f = 0; f < fields.length; ++f) {
row[fields[f]] = $(tr).find('.' + fields[f]).val();
}
// append row data to data array
data.push(row);
});
Here's a quick way to grab data from your table, and format it as an array:
var data_to_send = $('#yourtable').find('tr').map( function(idx){
return [
'row': idx+1,
'supp_short_code' : $(this).find('td').eq(2).text(),
'something_else' : $(this).find('td').eq(3).text() // etc
];
}).get();
Now you have data_to_send, an array formatted similarly to the example in your question. As #meagar points out, you can simply post this to the server with .ajax() et al., and allow jQuery to automatically handle the encoding. Something like this:
$.ajax ({
type: 'post',
url: 'your_script',
data: data_to_send
});

Categories