I am using jquery imagemapster to generate an image map with highlighted areas and tooltips on hover.
I have a 100 different areas and tooltips in my image (all with elements numbered 1-100) and all works well.
However, I want to write a function that will allow me to loop through each of these elements so I don't have to write the key and tooltip code 100 times. What is the best way for me to do this?
I have tried each() and for (i = 0; i < 100; i++) { //code here } but I think the looped output is causing errors.
Current code that needs the loop in the Areas section below. 3 lines shown as example of the 100.
Many Thanks
$(document).ready(function () {
$('img').mapster({
showToolTip: true,
toolTipContainer: '<div class="map_popup"></div>',
singleSelect : true,
clickNavigate : true,
mapKey: 'data-key',
fill : true,
areas: [
// below line needs to be looped. 3 examples shown
{ key: "1", toolTip: "<h3>Controller 1</h3>:<?php echo $Selected_1; ?>" },
{ key: "2", toolTip: "<h3>Controller 2</h3>:<?php echo $Selected_2; ?>" },
{ key: "3", toolTip: "<h3>Controller 3</h3>:<?php echo $Selected_3; ?>" },
// ...
]
});
Not sure what is going on with the $arraySelected in other answer & how that will loop 100 times.
I had a solution before generating data with javaScript, but that is going to render the <?php echo $Selected_1; ?> useless as this is done server-side and the js is done client-side.
Need to generate the areasData server-side. I would do:
// just data, don't need to wait until DOM is ready
// since you're outputting via PHP, you have to generate data with PHP
const areasData = [
<?php
$loopNo = 100;
for ($i = 1; $i <= $loopNo; $i++) {
echo '{ key: "' . $i . '", toolTip: "<h3>Controller 1</h3>:' . ${'Selected_' . $i} . '" }';
if ($i < $loopNo) {
echo ',';
}
}
?>
];
$(document).ready(function() {
// then reference the areas data
$("img").mapster({
showToolTip: true,
toolTipContainer: '<div class="map_popup"></div>',
singleSelect: true,
clickNavigate: true,
mapKey: "data-key",
fill: true,
areas: areasData
});
});
Umm, down voters explain why? Thanks.
EDIT: Try iterate through images like this:
$(document).ready(function() {
$('img').each(function(ix,ex){
$(ex).mapster({
showToolTip: true,
toolTipContainer: '<div class="map_popup"></div>',
singleSelect: true,
clickNavigate: true,
mapKey: 'data-key',
fill: true,
areas: [
<?php
foreach ($arraySelected as &$Selected) {%>
{
key: "1",
toolTip: "<h3>Controller <?php ech $Selected.id?></h3>:<?php echo $Selected.Text; ?>"
},
<?php}
?>];
});
});
});
Related
I want to draw one page with HighChart. I took data from database. I wrote it with json_encode. I can see what my $xxx has value. Its json format. But my graph is not working. I think var data = <?php echo json_encode($xxx); ?> doesnt work and return valur. Where do I mistake?
Here is my php code for database value:
<?php
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$no = 1;
$total_deger=count($data);
foreach($data as $dat)
{
$xxx ="[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
if($no < $total_deger)
{
echo ",";
}
echo json_encode($xxx);
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
?>
And here is my highchart script:
<script>
$(function () {
var data = <?php echo $xxx; ?>;
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: [data]
}]
});
});
</script>
Edit: I edited json format. When I write just echo. Its just see one value.
Edit2: I have 9 value. My output is:
,,,,,,,,[Date.UTC(2016,11,15,10,28,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,27,00),17]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,33,00),93]
[Date.UTC(2016,11,15,18,33,00),34]
[Date.UTC(2016,11,15,18,34,00),34]
But when ı read docs for highchart my value must be
([
[Date.UTC(2016,11,15,10,28,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,27,00),17],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,33,00),93],
[Date.UTC(2016,11,15,18,33,00),34],
[Date.UTC(2016,11,15,18,34,00),34]
]);
Try wrapping it in quotes
var data = "<?php echo json_encode($xxx); ?>"
You should see this as an error in the console
Also you arent concatenating correctly. This means every time the loop runs you are overwriting the last entry stored in $xxx
$xxx = "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
should be
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
Finally, change your loop to work like this
$xxx = '';
foreach($data as $dat){
// if not a blank string i.e. something added, add a comma to the end read for the next concatenation
if($xxx != '') $xxx .= ",";
// concatenate
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
}
// if not blank string, echo
if($xxx != ''){
echo json_encode($xxx);
}
I'm struggling with getting data to populate my MorrisJS bar chart using data from my mySQL database. Could anyone assist in getting it to display on my bar chart?
Below is my current code and pages.
<?php
$link = mysql_connect('127.0.0.1', 'root', 'password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('database') or die('Could not select database');
$dataArray=array();
//get data from database
$sql="SELECT * FROM table";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$Version=$row["Version"];
$Live=$row["Live"];
$Preprod=$row["Preprod"];
//add to data areray
$dataArray[$Version]=$count;
}
}
?>
index.php (main page)
div id="morris-bar-chart"></div>
<?php include ('database.php') ?>
<script src="../js/morris-data.js"></script> <----- script on index.php page linking to morris chart page.
morris.js page
Morris.Bar({
element: 'morris-bar-chart',
data: [{
while ($row = mysql_fetch_assoc($result)) {
y:<?=$row['versions']?>,
Live:<?=$row['Live']?>,
PreProd: <?=$row['Preprod']?>
}, {
],
xkey: 'y',
ykeys: ['Live', 'PreProd'],
labels: ['Live', 'PreProd'],
hideHover: 'auto',
resize: true
});
Hope this all makes sense. Thanks in advance.
I think the while is the problem.
Morris expects data line-wise, e.g. { y: '2007', a: 75, b: 65 },
I've adjusted the PHP code part in the morris.js script a bit.
Normally, you can not execute PHP within a JS file. Except, when you added a rule to the server, that JS files should be processed by PHP, too.
The normal way to fetch the data would be an AJAX query to a PHP script, which returns the json_encoded($result). And then add it to Morris with the setData() function.
But this should work, too: generate the JS file by PHP. You could rename the morris-data.js to morris-data.js.php. The file needs <?php header("Content-type: application/javascript"); ?> at the top. And then adjust your <script include to match the new filename.
File morris-data.js.php
<?php header("Content-type: application/javascript"); ?>
Morris.Bar({
element: 'morris-bar-chart',
data: [
<?php
while ($row = mysql_fetch_assoc($result)) {
// output a line like:
// { y: '123', Live: 123, PreProd: 123 },
sprintf(
"{ y: '%s', Live: %s, PreProd: %s },",
$row['version'],
$row['Live'],
$row['Preprod']
);
}
?>
],
xkey: 'y',
ykeys: ['Live', 'PreProd'],
labels: ['Live', 'PreProd'],
hideHover: 'auto',
resize: true
});
that should render something like (see also the bar chart example)
data: [
{ y: '1.2.3', Live: 20, PreProd: 23 },
{ y: '1.2.4', Live: 30, PreProd: 24 },
{ y: '1.2.5', Live: 40, PreProd: 25 },
{ y: '1.2.6', Live: 50, PreProd: 26 }
],
(I'm not sure what the last part in the database.php file is supposed to do.
Maybe you can drop that (the code inside the if($result)). But maybe its for calculations..)
I'm looking to use highcharts to display quantity (0.0) and time (HH:MM).
The quantity and time will be selected from a database.
At this point I have made a working example but the data from the database is weight (0.0) and age (weeks). This data was easy to put into the chart and has worked perfectly. The code I have used for this is shown below;
<?php
session_start();
// Create connection
$con=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_SESSION['id'];
$response = mysqli_query($con,"SELECT b_id,weight,age FROM tbl WHERE id = '".$id."' ");
if(!$response)
{
die("<p>Error". mysqli_error($con)."</p>");
}
$weight = array();
$age = array();
while($result=mysqli_fetch_array($response))
{
$weight += [$result['b_id'] => $result['weight']];
$age += [$result['b_id'] => $result['age']];
}
?>
// High Chart //
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: [<?php echo join($age, ',');?>],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: ''
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
data: [<?php echo join($weight, ',');?>]
}]
});
});
</script>
I now need to create a graph to show the quantity (0.0) and time (HH:MM) in a similar way. I know that the time must be converted into milliseconds for it to work with JavaScript for which I did find some code for from stack overflow courtesy of Tim Cooper:
<?php $str_time = $time;
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
?>
I just need to know if and how to make this work with the highcharts in the way that I have used them using php rather than using JSON to get the data.
Also if instead i need to reformat the time(HH:MM) to milliseconds before it is inserted into the database so that it can be selected and put into the array to use with the highcharts?
I'm slightly new to JavaScript so if anyone has any hints or tips on how to get this graph to work - preferably using similar syntax to the first graph it would be much appreciated!
Thanks!
beginner here, I'm trying to build a column graph that shows a username on the x axis, and a test score on the y axis. In the tooltips box, I'm trying to make it so it shows the test score and the date the test was taken. I'm using PHP to populate the graph based on an oracle sql database, so I'm mixing PHP into my javascript for Highcharts.
I'm not sure if what I'm trying to do is actually possible, but I'm trying to take the test date from the sql database, and plug it into the series data, so I can call it out into the tooltips box (that way when you hover over the column, it'll tell you the user, the score, and the date they took the exam).
This is what I'm trying, and it isn't working, because I'm guessing series data has something against strings instead of numeric. Any help you can offer would be awesome! Thanks!
<br><br><br><br>
<div id="graph1" style="height: 400px; width: <?php echo $chartspace ?>px"></div>
<input id="width" type="range" value="<?php echo $chartspace ?>" min="300" max="<?php echo $chartspacemax ?>" />
<script>
$(function () {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: [
<?php
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count); ?>
]
},
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: [
<?php
$i = 0;
do {
if($userinfos[$i]['score'] >= 85){
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: '#00A6CF'},";}
else{
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: 'red'},";}
$i++;
} while ($i<=$count-1); ?>]
}],
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
$('#width').bind('input', function () {
$('#graph1').highcharts().setSize(this.value, 400, false);
});
});
</script>
What you're trying to do should definitely be possible. Here's an example of that working:
http://jsfiddle.net/thfbx7gb/
However, in this case I pulled out the PHP and replaced it with some hard-coded data.
data: [{y:7, color: '#00A6CF', testdate: '2014-12-12'},{y:2, color:"#FF0000", testdate: '2015-01-03'}, {y:3,color:"#00FF00", testdate:'2014-10-19'}]
So I think the problem is that you're mixing in PHP with javascript and getting some strange results. It's generally a very bad idea to include inline PHP into javascript code like you're doing if for no other reason that it's really, really hard to read and debug.
A few things jump out at me:
You shouldn't be using PHP for this at all, but if you must then you shouldn't be using do-while loops like you are. You're using a do/while with an incrementor instead of a for loop:
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count);
This should really be:
for ($i=0; $i<=$count; $i++) {
echo "'{$userinfos[$i]['username']}'";
}
You should be able to see how the other do/while loops you're using could be reduced to a much more succinct for loop.
But that still doesn't eliminate the whole problem of including PHP code in your javascript. You should really be either hard coding this data or loading it from an external source of some kind. The typical way of doing that would be with an AJAX call to load the data and then pass that in to the chart directly.
You would have a file that generates the data object directly and outputs that as as JSON string using json_ecode();
$output = array();
foreach ($userinfos as $user) {
$output['categories'][] = $user['username'];
if ($user['score'] >= 85) {
$color = "#00A6CF";
} else {
$color = "#FF0000";
}
$user['color'] = $color;
$output['seriesdata'][] = $user;
}
echo json_encode($output);
This should give you a JSON object which you can read work with pretty easily. Something along the lines of this (which is untested, it may not work without a bit of fiddling):
$.getJSON('/generate.php', function(data) {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: data.categories
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: data.seriesdata,
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
});
I am trying to update jqplot PieChart via JS since yesterday and I am not having any breakthrough with this. I have searched online and cant seem to get any solution work
The chart data is saved in session and this session is continuously being updated by the application.
This is what the JSON looks like
[ ['Take home pay', 44228.33], ['Tax', 8771.67], ['Super', 4162.5 ], ['Regular expenses', 0 ], ['Unallocated', 44228.33], ['Testing', 8000] ]
The chart loads fine when the user navigates to the page for the first time.
This is the DIV where the chart loads
<div id="savings_expense" class="jqplot-target"></div>
This is the jqplot JS when the page loads which works fine
$(document).ready(function () {
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
});
This is the button that user clicks to update the chart.
<li onclick="updateGraph()">YOUR TAKE-HOME PAY</li>
I have tried two ways to update the PieChart
Solution 1
In this solution I get the error Uncaught TypeError: Cannot read property 'replot' of undefined.
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
function renderGraph() {
plot1.replot({
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
});
}
function updateGraph() {
alert('updateGraph');
var newVal = <?php echo $_SESSION['chart_data'] ?>;
storedData.push(newVal);
renderGraph();
}
Solution 2
In this solution the pie chart goes blank but the legends stay
var storedData = <?php echo $_SESSION['SMP']['chart_data'] ?>;
var plot1;
function renderGraph() {
if ( plot1) {
plot1.destroy();
}
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense',[storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
}
I will really appreciate any help here. Please do not share any links as I have gone through about every solution I could find on StackOverflow and on net
You have to keep on document.ready code as it is and then add function updateGraph outside document.ready (keep all variable at global level). Also modify updateGraph, here you need to call .replot() on plot1 variable as you are only changing data and not other setting.
put id to li like this : <li id="updateGraph">YOUR TAKE-HOME PAY</li>
See below code :
// declare variable outside document.ready
var plot1;
var storedData;
$(document).ready(function () {
storedData = <?php echo $_SESSION['chart_data'] ?>;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
$('#updateGraph').click(function(){updateGraph();});
});
function updateGraph() {
var newVal = <?php echo $_SESSION['chart_data'] ?>;
plot1.destroy();
plot1.series[0].data = newVal;
plot1.replot(true);
}