Highcharts doesn't update from file - php

I use Highcharts and when I update the site it doesn't update the data from which it constructs the graph.
I take the data from mysql, save it in a .csv file and open the .csv in highcharts. It seems to save the old values in the graph even if the .csv file is updated.
<?php
unlink('column-data.csv'); //This file must exist or else it gives error
include 'database.php';
$result = mysql_query("SELECT
value
FROM
data
INTO OUTFILE 'C:/xampp/htdocs/arduinoproj/test3/column-data.csv'
FIELDS ENCLOSED BY '\,'
TERMINATED BY ';'
ESCAPED BY '\"'
")
or die("Could not issue MySQL query");
include 'highcharts.php'
?>
..and the highcharts code is more or less unchanged.
The changed code from the original is in bold.
Highcharts code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My first column chart by Highcharts</title>
<!-- 1. Add JQuery and Highcharts in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!-- 2. You can add print and export feature by adding this line -->
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- 3. Add the JavaScript with the Highchart options to initialize the chart -->
<script type="text/javascript">
jQuery(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
**type: 'line'**
},
title: {
text: 'Tiny Tool Monthly Sales'
},
subtitle: {
text: '2014 Q1-Q2'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Sales'
}
},
series: []
};
// JQuery function to process the csv data
$.get(**'column-data.csv'**, function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains names of categories
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
//skip first item of first line
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
//putting all together and create the chart
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Related

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

Not able to export jqgrid table as excel/pdf.

I successfully created a small jqgrid table. I'm trying to export this table to an excel or pdf file using Jquery. I am new to jquery and jqgrid. Could someone please let me know what is wrong in the code? I would really appreciate some help or suggestions.
I found the export function online. It said I have to just call this function with the grid id. Am I doing something wrong?
export.php file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="CSS/CalibrationKit.css" rel="stylesheet" type="text/css">
<!-- ------------------------JQGRID files-------------------------------- -->
<link rel="stylesheet" type="text/css" media="screen" href="jquery/css/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="jquery/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="jquery/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="jquery/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
/*jqgrid*/
var mydata = [{
head_mean_volume: "50",
head_std_dev: "2",
head_cv: "3",
offset_factor: "4",
scaling_factor: "5"
}];
$("#projectSpreadsheet").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Head Mean Volume Dispensed", "Head Standard Deviation", "Head %CV", "Whole Head Offset Factor", "Whole Head Scaling Factor"],
colModel: [{
name: 'head_mean_volume',
index: 'head_mean_volume',
editable: false,
}, {
name: 'head_std_dev',
index: 'head_std_dev',
editable: false,
}, {
name: 'head_cv',
index: 'head_cv',
editable: false,
}, {
name: 'offset_factor',
index: 'offset_factor',
editable: false,
}, {
name: 'scaling_factor',
index: 'scaling_factor',
editable: false,
}],
'cellEdit': false,
'cellsubmit' : 'clientArray',
editurl: 'clientArray'
}); /*jqGrid close */
/* createExcelFromGrid */
$('#btnSun').click(function() {
$.fn.myFunction("projectSpreadsheet");
});
$.fn.myFunction = function(gridID,filename) {
var grid = $('#' + gridID);
var rowIDList = grid.getDataIDs();
var row = grid.getRowData(rowIDList[0]);
var colNames = [];
var i = 0;
for(var cName in row) {
colNames[i++] = cName; // Capture Column Names
}
var html = "";
for(var j=0;j<rowIDList.length;j++) {
row = grid.getRowData(rowIDList[j]); // Get Each Row
for(var i = 0 ; i<colNames.length ; i++ ) {
html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
}
html += '\n';
}
html += '\n';
var a = document.createElement('a');
a.id = 'ExcelDL';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename ? filename + ".xls" : 'DataList.xls';
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('ExcelDL').remove();
}
}); /* function close */
</script>
</head>
<body>
<table id="projectSpreadsheet" class="fixed_headers" style="width:875px"></table>
<br><br>
<button id="btnSun">Export Table data into Excel</button>
</body>
</html>
Replace your function with this one and let me know if it works for you.
function(gridID,filename) {
var html = $('#gview_' + gridID).html();
var a = document.createElement('a');
a.id = 'tempLink';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename + ".xls";
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('tempLink').remove();
}

Show results from database in jquery

How can I use the content in $displayusercontent which is pulled from the db into the Text field on the jquery.
I've tried this below, but nothing returns, if I echo $displayusercontent on to the page then it works this way.
<html>
<head>
</head>
<body>
<!-- my content here-->
<script type="text/javascript">
var userContent = <?php echo $displayusercontent; ?>
</script>
<script type="text/javascript" src="/my/javascript/file/here.js"></script>
</body>
</html>
This is from my jquery file
initIntro: function () {
// display marketing alert only once
if (!$.cookie('intro_show')) {
setTimeout(function () {
var unique_id = $.gritter.add({
// (string | mandatory) the heading of the notification
title: 'MyTitle',
// (string | mandatory) the text inside the notification
text: userContent,
// (string | optional) the image to display on the left
//image: '../../assets/local/layout/img/avatar.png',
// (bool | optional) if you want it to fade out on its own or just sit there
sticky: true,
// (int | optional) the time you want it to be alive for before fading out
time: '',
// (string | optional) the class name you want to apply to that specific message
class_name: 'my-sticky-class'
});
// You can have it return a unique id, this can be used to manually remove it later using
setTimeout(function () {
$.gritter.remove(unique_id, {
fade: true,
speed: 'slow'
});
}, 15000);
}, 2000);
$.cookie('intro_show', 1);
}
}
It's invalid. You need to make it a string
var userContent = <?php echo json_encode($displayusercontent); ?>;
As #dsclementsen pointed out, in this case using json_encode is the right option.
After the posts and reading the links attached, this is my code that works.
<html>
<head>
</head>
<body>
<!-- my content here-->
<script type="text/javascript">
var userContent = <?php echo json_encode($displayusercontent) ?>;
</script>
<script type="text/javascript" src="/my/javascript/file/here.js"></script>
</body>
</html>
Thanks all for the help :-)

Manage multiple highchart charts in a single webpage with PHP

In my page, i have an options to choose if i want to show one chart or all chart, in the same time.
When i choose all chart to view, it's OK.
When i choose "chart a" it's OK.
When i choose "chart b" it does'n show any chart.
I remark that when i choose "chart a" or all charts, it display the both alert.
When i choose "chart b", it display only the first alert.
Am I doing something wrong?
Any help will be much appreciated.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
chart: {
defaultSeriesType: 'spline',
},
xAxis: {
type: 'datetime',
},
});
var options1 = {
chart: {
renderTo: ''
},
series: []
};
var options2 = {
chart: {
renderTo: ''
},
series: []
};
alert("chart1");
options1.series.push({name: "Temperatura",data: _VARS['data1'],lineWidth: 1,color: '#3e5bc1'});
options1.chart.renderTo = 'chart_1';
var chart1 = new Highcharts.Chart(options1);
alert("chart2");
options2.series.push({name: "HR",data: _VARS['data2'],lineWidth: 1,color: '#3e5bc1'});
options2.chart.renderTo = 'chart_2';
var chart2 = new Highcharts.Chart(options2);
});
</script>
</head>
<body>
<script>
var _VARS = new Array();
_VARS['data1'] = [[Date.UTC(2012,7,14,12,0),26.1],[Date.UTC(2012,7,14,13,0),27.2],[Date.UTC(2012,7,14,14,0),28],[Date.UTC(2012,7,14,15,0),28.4],[Date.UTC(2012,7,14,16,0),27.1],[Date.UTC(2012,7,14,17,0),27.2],[Date.UTC(2012,7,14,18,0),26.1],[Date.UTC(2012,7,14,19,0),24.8],[Date.UTC(2012,7,14,20,0),22.5],[Date.UTC(2012,7,14,21,0),21.3],[Date.UTC(2012,7,14,22,0),20.1],[Date.UTC(2012,7,14,23,0),19],[Date.UTC(2012,7,15,0,0),18.3]];
VARS_AMBIENTE['data2'] = [[Date.UTC(2012,7,14,12,0),43],[Date.UTC(2012,7,14,13,0),44.1],[Date.UTC(2012,7,14,14,0),46.8],[Date.UTC(2012,7,14,15,0),49.3],[Date.UTC(2012,7,14,16,0),60.1],[Date.UTC(2012,7,14,17,0),57],[Date.UTC(2012,7,14,18,0),60.7],[Date.UTC(2012,7,14,19,0),69.5],[Date.UTC(2012,7,14,20,0),77.8],[Date.UTC(2012,7,14,21,0),80.5],[Date.UTC(2012,7,14,22,0),81.4],[Date.UTC(2012,7,14,23,0),83.1],[Date.UTC(2012,7,15,0,0),85.3]];
</script>
<h2>Choose Chart Test</h2>
<?php
// when i choose a, it's OK
// when i choose b, it's NOT OK
// when i choose c, it's OK
//$param ="a";
$param ="b";
//$param ="c";
if($param == 'a'){
echo "<p>chart a</p>
<div id='chart_1'></div>";
}elseif($param == 'b'){
echo "<p>chart b</p>
<div id='chart_2'></div>";
}else{
echo "all charts\n";
echo "<p>chart a</p><div id='chart_1' ></div></br></br>";
echo "<p>chart b</p><div id='chart_2'></div></br></br>";
}
?>
</body>
</html>
When you have chosen option b) the line:
var chart1 = new Highcharts.Chart(options1);
cause an error in javascript and the execution of the script is stopped. Highcharts could not find a chart_1 div and exits with error. When you choose option a) script go through this line but stops on this line:
var chart2 = new Highcharts.Chart(options2);
and you even do not notice this. Check in developer tools (Chrome or Firefox), there is an error in javascript console. I did it and in situation b) there is and error: Highcharts Error #13: Rendering div not found
To get it right you should check whether each of divs exists in html. Try using jQuery for this:
alert("chart1");
options1.series.push({name: "Temperatura",data: _VARS['data1'],lineWidth: 1,color: '#3e5bc1'});
options1.chart.renderTo = 'chart_1';
// checking if div#chart_1 exists
if ($("#chart_1").length > 0) {
var chart1 = new Highcharts.Chart(options1);
}
alert("chart2");
options2.series.push({name: "HR",data: _VARS['data2'],lineWidth: 1,color: '#3e5bc1'});
options2.chart.renderTo = 'chart_2';
// checking if div#chart_2 exists
if ($("#chart_2").length > 0) {
var chart2 = new Highcharts.Chart(options2);
}

How can we echo data for Progress bar in PHP?

We are working on a ProgressBar using Jquery UI. We are facing some problems, that we aren't getting values from PHP. We are unable to make a numerical loop that can return the value to Ajax based code.
Below is our code:
HTML
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#bardivs {
width:400px; /* or whatever the of the porgress bar is */
/*
The position of #bardivs must be something other than
static (the default) so that its children will be positioned
relative to it.
*/
position:relative;
}
#progresstext {
position:absolute;
top:0;
left:0;
}
</style>
<script>
var url = "http://localhost/sample/data.php";
$(function() {
var progress = 0;
//alert("some value" + value, value);
$("#progressbar").progressbar({ progress: 0 });
setTimeout(updateProgress, 500);
});
function updateProgress() {
var progress;
$.get(url, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar("option", "value", data);
$("#progresstext").html("<p> Loading...<p>");
setTimeout(updateProgress, 500);
} else {
$("#progressbar")
.progressbar("option", "value", 100);
}
});
}
</script>
</head>
<div id="bardivs">
<div id="progressbar"></div>
<div id="progresstext"></div>
</div>
</html>
We don't have any idea how can we make the code in PHP use this loading function. It should in a loop.
There is no such progress: 0, the progress is measured by value and you should make the data INT because it comes as string:
$("#progressbar").progressbar({ value: 0 });
setTimeout(updateProgress, 500);
});
function updateProgress() {
var progress;
$.get(url, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar({value: parseInt(data)});
$("#progresstext").html("<p> Loading...<p>");
setTimeout(updateProgress, 500);
} else {
$("#progressbar").progressbar({value: 100});
}
});
}
In php make sure you update the progress based on your scripts
<?php
$data = get_progress();
echo (int)$data;
?>

Categories