Multiple graphs in php loop - php

I have a problem with google charts. I developed a web page with 5 (generated with php) and 5 ID for each :
echo "<div id = \"ID\" style=\"display:none;\">"
I also have 5 json arrays with all the information. I show in each the data in a table but I would like also show a graph with my data.
I tried to do in this way (but it doesn't work):
for ($i = 0; $i<$n;$i++){
$jsonTable = json_encode(${'table'.$Result_array[$i][1]});
$ID = $Result_array[$i][1]; //ID for the div
echo "<script type=\"text/javascript\">
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart());
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(".$jsonTable.");
var options = {
title: 'Company Performance',
hAxis: {title: 'L value', titleTextStyle: {color: 'red'}, gridlines:{count:10} },
vAxis: {
title: \"I rms\",
maxValue:1.5,
gridlines:{count:10}
}
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
chart.draw(data, options);
}
}
</script>";
}
If I use this code only for 1 table, works fine, but when I use a loop and try to generate multiple graphs, it doesn't work.
Anyone could help me? thanks!
P.S: Maybe I also have to explain that, first of all, I have a table with my 5 results, and when I click, I have a onclik function to unhide the appropiate . This works always (with graphs and without it) but never display the graphs....

Where are the 5 ids you are looping through only one id
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
It should be like this
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."_".$i"'));
and add the div like
echo "<div id = \"ID_0\" style=\"display:none;\">"
echo "<div id = \"ID_1\" style=\"display:none;\">"
echo "<div id = \"ID_2\" style=\"display:none;\">"
echo "<div id = \"ID_3\" style=\"display:none;\">"
echo "<div id = \"ID_4\" style=\"display:none;\">"

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\\\\\\

Data from MySQL to JSON to AJAX within PHP website, how?

I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying.
Basically, I do have a database with data for gym exercises
CREATE TABLE IF NOT EXISTS `gp_progs` (
`prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`exer` varchar(250) NOT NULL,
`pic` varchar(15) NOT NULL,
PRIMARY KEY (`prog_id`),
UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `gp_progs`
--
INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');
I have treated it after digging the code for many hours with this code in PHP
$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = #mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
$json[] = $row;
}
$jsondata = json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
echo 'Data successfully saved';
}
It gave me a json file from which I realy want to build AJAX functional app like this one.
JS:
$(function() { // When the DOM is ready
var times; // Declare global variable
$.ajax({
beforeSend: function(xhr) { // Before requesting data
if (xhr.overrideMimeType) { // If supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
// FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
function loadTimetable() { // Declare function
$.getJSON('data/events.json') // Try to collect JSON data
.done( function(data){ // If successful
times = data; // Store it in a variable
}).fail( function() { // If a problem: show message
$('#event').html('Sorry! We could not load the timetable at the moment');
});
}
loadTimetable(); // Call the function
// CLICK ON THE EVENT TO LOAD A TIMETABLE
$('#content').on('click', '#event a', function(e) { // User clicks on event
e.preventDefault(); // Prevent loading page
var loc = this.id.toUpperCase(); // Get value of id attr
var newContent = ''; // Build up timetable by
for (var i = 0; i < times[loc].length; i++) { // looping through events
newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
newContent += '<a href="data/descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page
$('#event a.current').removeClass('current'); // Update selected item
$(this).addClass('current');
$('#details').text(''); // Clear third column
});
// CLICK ON A SESSION TO LOAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function(e) { // Click on session
e.preventDefault(); // Prevent loading
var fragment = this.href; // Title is in href
fragment = fragment.replace('#', ' #'); // Add space after#
$('#details').load(fragment); // To load info
$('#sessions a.current').removeClass('current'); // Update selected
$(this).addClass('current');
});
// CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function(e) { // Click on nav
e.preventDefault(); // Prevent loading
var url = this.href; // Get URL to load
$('nav a.current').removeClass('current'); // Update nav
$(this).addClass('current');
$('#container').remove(); // Remove old part
$('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
});
});
HTML:
<section id="content">
<div id="container">
<h2>Upcoming Events in Yorkshire</h2>
<div class="third">
<div id="event">
<a id="sh" href="sh.html"><img src="img/sheffield.fw.png" alt="Sheffield, South Yorkshire" />Sheffield</a>
<a id="hu" href="hu.html"><img src="img/hull.fw.png" alt="Hull, East Yorkshire" />Hull</a>
<a id="ls" href="ls.html"><img src="img/leeds.fw.png" alt="Leeds, West Yorkshire" />Leeds</a>
<a id="yk" href="yk.html"><img src="img/york.fw.png" alt="York, West Yorkshire" />York</a>
</div>
</div>
<div class="third">
<div id="sessions">
<p>Select an event from the left</p>
</div>
</div>
<div class="third">
<div id="details"></div>
</div>
</div><!-- #container -->
</section><!-- #content -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/events.js"></script>
So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.
If something is not clear please let me know as I am still learning how to use overflow.
Thanks in advance!
This is for PHP website with an use of JS, MySQL, Google API and HTML of course.
Edit:
If it was not too clear, I want to get MySQL data to JSON (which I have done already)
[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]
And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below:
I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.
Here's how I do it. The key here is the use of str_replace.
PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):
$subcategorydata =
SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories =
str_replace('\\"','\\\\"',
str_replace("'","\'",
json_encode($subcategorydata)));
Javascript (direct rather than via ajax in my case):
var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....
EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.
Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.
<div id=main></div>
<script>
function set(div, value) {
document.getElementById(div).innerHTML = value;
}
function hide(div) {
var x = document.getElementById(div);
x.style.display = "none";
}
function show(div) {
var x = document.getElementById(div);
x.style.display = "block";
}
function toggle(div) {
var x = document.getElementById(div);
if (x.style.display === "none") { show(div); } else { hide(div); }
}
var json='[{"heading":"This is the first heading","detail":"This is the first detail"},{"heading":"This is the second heading","detail":"This is the second detail"}]';
var jsonData = JSON.parse(json);
var html = '';
for (var row in jsonData)
{
html += '<div id=hdr' + row + ' onclick=toggle(\'dtl' + row + '\')>';
html += '<b>' + jsonData[row].heading + '</b></div>';
html += '<div id=dtl' + row + '>' + jsonData[row].detail + '</div>';
}
set('main','Click on the headings to toggle the detail<br>' + html);
for (var row in jsonData)
{
hide('dtl' + row);
}
</script>
you have the name of the image already in the records and you should also know, were on the server the images can be found.
You can combine this knowledge and forge a URI from path and filename

Using PHP with charts and MySQL data

I'm using google charts to output a very simple pie chart
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', 11],
['Lose', 2]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
However, in place of the values for Win and Lose, I want to pull 2 numbers out of my database. This doesn't need any kind of loop, just a way to reference 2 specific fields on a row instead of the values 11 and 2. This is the SQL query I'm using to get those two values
$qry =("SELECT games_won, games_lost FROM Members where member_id = '".$_SESSION['SESS_MEMBER_ID']."'");
$result = mysql_query($qry);
$row = mysql_fetch_array($result);
$won = $row[games_won];
$lost = $row[games_lost];
Does anyone know how to do this?
I've had a look at a lot of other FAQ's on the subject but they all deal with a collection of values in the same field and looping through severals rows of data, as opposed to referencing specific entries in the database.
Thanks in advance!
Have you tried this:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', <?php echo($won); ?>],
['Lose', <?php echo($lost); ?>]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
All you are doing is grabbing the values, then echoing them out into your JavaScript. Please do note that I am not error checking, that is something you will need to think about when directly injecting values into HTML or JavaScript!
A better way of doing this is writing your code as a RESTful API. Have your SQL code in a place that you can send a member_id as a GET request. That, in turn, can print out the games won/lost inside JSON. Than, you can preform an AJAX request and grab those values to populate your table (just reference the values inside the returned JSON as regular JavaScript variables).

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

google charts api - pie chart is not displaying

I am trying to create a piechart dynamically by using Google Chart api. i am taking values from the database. I am not getting how exactly this can be done.
$resultViewed = $this->model_report_product->getMostViewed();
$stringResult ="var data= google.visualization.arrayToDataTable([ ['Product', 'Views'],";
foreach($resultViewed as $results)
{
$stringResult = $stringResult . "['".$results['name']."',".$results['quantity']."],";
break;
}
$stringResult .= "]);";
$this->data['Viewed'] = $stringResult;
When i run this, it gives Chart heading but pie chart is not displayed but it says No Data.
You can't pass a variable in memory between php to html. You have to print it out to pass it to html. So where you have:
return $stringResult;
you should print it out like:
print $stringResult;

Categories