Related
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}
?>];
});
});
});
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 want to show data recieved from MySQL in Highchart.js graphic. For that, I'm using two textboxes which being entered to date informations. Finally, using a single button which calls function (chart.php). By the way, I'm getting date informations and sending to mysql.php with $.post method in the function. Then I want to get MySQL datas to show in Highchart.js. But program is giving me empty array. Actually, array have a lot of datas, because function(data) is showing datas in the ($.post).
chart.php
function zaman_al()
{
var baslangic=document.getElementById('rest_example_3').value;
var son=document.getElementById('rest_example_4').value;
if (baslangic=="" || son=="")
{
alert("Lütfen Tarih bilgisi Giriniz !!!");
}
else
{
baslangic = new Date(baslangic);
baslangic = baslangic.getTime();
son = new Date(son);
son= son.getTime();
if (son<=baslangic)
{
alert("Geçersiz Tarih Girişi !!!");
}
if (son>baslangic)
{
var veri={'baslama':(baslangic/1000),'bitirme':(son/1000)};
$.post('mysql.php',veri,
function(data)
{
alert(data);
$(function () {
$('#kku').highcharts({
chart: {
type: 'spline'
},
title: {
text: 'Snow depth at Vikjafjellet, Norway'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Snow depth (m)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
series: [{
name: 'Winter 2007-2008',
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
data: [
<?php
$veri=explode('"',$sonuc);
for ($i = 0; $i < count($veri); $i++)
{
if(($i%4)==1)
{
echo "[".$veri[$i].","; // time
}
if(($i%4)==3)
{
echo $veri[$i]."],\n"; // sensor_value
}
};
?>
]
}]
});
});
});
}
}
}
Above code for button function. By the way.
chart.php
<b>Başlangıç Zamanı :</b> </td>
<td><input style="border-radius:15px" type="textbox" name="rest_example_3" id="rest_example_3" value="" /></td>
<td ><br><br><br></td>
</tr>
<tr>
<td><b>Bitiş Zamanı :</b> </td>
<td><input style="border-radius:15px" type="textbox" name="rest_example_4" id="rest_example_4" value="" /></td>
<td ><br><br><br></td>
</tr>
<tr>
<td ><br><br><br></td>
<td><input type="button" style="border-radius:15px; background-color:lightgreen; float:right" width="100" value="Get Chart" onClick="zaman_al()"> </td>
<td ><br><br><br></td>
</tr>
</table></center>
<div id="kku"></div>
When I sent to data mysql.php in the ($.POST), mysql.php is giving me notice:Undefined xxx.
mysql.php error statement
By the way, mysql.php is follow as:
<?php
$baslangic =$_POST['baslama']; // -> notice: Undefined index: baslama
$son=$_POST['bitirme']; // -> notice: Undefined index: bitirme
//$baslangic=1445780257; -> correct result for it
//$son=1445780290; -> correct result for it
//echo $son;
//echo $baslangic;
//settype($son, "int");
//settype($baslangic, "int");
//echo gettype(1445780290);
//echo gettype($son);
$baglanti= new mysqli("localhost","root","","deneme_kou");
$sql = "SELECT zaman,sensor_deger FROM sensor WHERE zaman>='$baslangic' AND zaman<='$son'";
$res=mysqli_query($baglanti,$sql);
$result = array();
while( $row = mysqli_fetch_array($res))
{
$result[]=array($row["zaman"],$row["sensor_deger"]);
}
$sonuc=json_encode(array($result));
echo json_encode(array($result));
?>
When I wrote $baslangic=1445780257 $son=1445780290; instead of $baslangic = $_POST['baslama']; $son=$_POST['bitirme'], I can get correct result and show in highchart.js.
Could you help me about this problem?
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>'
}
});
});