fetching data from mysql databases - javascript

Hello everyone is there any possibly to fetch data from mysql databases in javascript . For example i have the following code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/highcharts.js"></script>
<!-- 1a) Optional: add a theme file -->
<!--
<script type="text/javascript" src="../js/themes/gray.js"></script>
-->
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="../js/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 500);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
</script>
</head>
<body>
from this code
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
instead of random no i want to fetch from the database . please guide

You can't connect to a MySQL database from traditional Javascript. You'll have to do that server-side, such as in PHP.
There are some in-between solutions, such as Jaxer, (A tutorial here.), but this would probably be a bit over your head.

No, there's (fortunately) no express-way from JavaScript to MySQL. You'd have to make requests against some custom HTTP-based service (written in whatever programming language) that then accesses MySQL.

Make an AJAX request to the PHP script (using jQuery or whichever way you prefer), and get the PHP script to give you back JSON data of the row using json_encode

Related

HighChart- Wrong Datetime in the X-Axis for Live Chart

I am using HighChart for Live Chart (Data changes each 10 seconds).In each Second , an ajax call will take place and get the data from the Controller as json. In the example , I can get the data in each 10 seconds but the time shows in the X-axis is wrong. Instead of showing the correct time , it showing the time more than 4 from the current time.
This is the HTML+js file
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
#*//Add JQUERY*#
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
#*//Add HighChart.js*#
<script src="http://code.highcharts.com/highcharts.js"></script>
<script>
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: getData
}
},
title: {
text: 'Live Bin Usage'
},
xAxis: {
type:'datetime',
tickPixelInterval: 150
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Time'
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function getData() {
$.ajax({
url: '/AswinDemo/FetchData',
dataType: 'json',
success: function (data) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
var x = (new Date()).getTime(), // current time
y = Math.random();
// add the point
chart.series[0].addPoint([x ,data.BinUsage], true, shift);
// call it again after one second
setTimeout(getData, 1000);
},
cache: false
});
}
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
The server or Controller
public ActionResult FetchData()
{
Random rn = new Random();
return Json(new { BinUsage = rn.Next(), Time = DateTime.Now.TimeOfDay.ToString()} ,JsonRequestBehavior.AllowGet );
}
Below is the Screen Shot of the Chart : -
You can see the time in my chart is deffer from the time of the PC (in the task bar)
I have solved the problem by setting global.useUTC to false. Thanks.

how to convert high charts code to nvd3.js

Here is my High Chart code for showing live Bitcoin Charts. I really am a noob at PHP, JavaScript etc, so i really need help in converting this code to nvd3.js
PHP Code:
<?php
// Set the JSON header
header("Content-type: text/json");
function getPrice($url){
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btce = getPrice('https://btc-e.com/api/2/btc_usd/ticker');
$btcePrice = round($btce["ticker"]["last"], 2);
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
// Create a PHP array and echo it as JSON
$ret = array($x, $btcePrice);
echo json_encode($ret);
?>
HTML and Javascript Code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'x.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 175; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 3000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Average price chart'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'USD',
margin: 80
}
},
series: [{
name: 'Live BTC USD Chart',
data: []
}]
});
});
</script>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
any help in explaining how to convert this code to work with nvd3.js would be greatly appreciated
Thanks!

Highcharts renders the other graph's data too

I have one html page where there are two divs. In each div I am loading different jsp files(one.jsp and two.jsp).
home.html:
<script src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/highcharts.js"></script>
<script type="text/javascript" src="resources/js/exporting.js"></script>
<script type="text/javascript" src="resources/js/export-csv.js"></script>
<script>
function loadGraphs()
{
$('#plotContainer1').load('one.jsp');
$('#plotContainer2').load('two.jsp');
}
</script>
where plotContainer1 and plotContainer2 are two divs. So that I want to load two graphs at a time.
one.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<div id="container1" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<script type="text/javascript">
var seriesArray;
var chart;
callAjax();
var graphTitle = "";
var chart;
function drawgraph1() {
Highcharts.setOptions({
colors: ['#54CBE5', '#57B442']
});
chart = $('#container1').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: graphTitle
},
xAxis: {
tickInterval: 30,
type: 'datetime',
categories: xAxisCategories
},
yAxis: {
min : 0,
title: {
text: ''
},
plotLines : [ {
value : 0,
width : 1,
color : '#808080'
} ]
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
series : seriesArray
});
};
function callAjax() {
$("#container1").empty();
seriesArray = [{
name: 'line1',
data: []
}, {
name: 'line2',
data: []
}];
xAxisCategories = [];
var params = {"param1" : value};
$.getJSON("graph1datafetcher",params, function(data) {
$.each(data, function(key, val) {
var xaxisPoints=data[key];
xAxisCategories.push(Date.parse(key));
for(var i in xaxisPoints) {
seriesArray[i].data.push(xaxisPoints[i]);
}
});
console.log(" JSON: " + JSON.stringify(data));
drawgraph1();
});
}
</script>
</body>
</html>
two.jsp almost contains the same code. Now first two.jsp loads as it contains less data compared to one.jsp. When one.jsp loads in and shows up in div, the one.jsp graph shows two.jsp data and its own data too. I am logging the data in the console, the data that is coming is fine. So, the problem is somewhere the highchart persists the first data. I have been struggling with this for past 7 hours. Can someone please answer how to resolve this?

Highcharts Won't load from php json, but it could load from data.json file

I tried to make a highchart from JSON data. I make a php file that generating the json and insert the address to the getJSON() like this.
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {...
and it wont work, so i decided to put the php inside the highcharts file like this.
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$resu = array();
$measurement = $_POST["choosenmeasurement"];
for($i = 0; $i < count($_POST["choosenbusid"]); $i++)
{
$busid = $_POST["choosenbusid"][$i];
$clusid = $_POST["choosenclusterid"][$i];
$fieldname = ''.$measurement.'_BUSID_'.$busid.'_CLUSTERID_'.$clusid;
$sql= "SELECT unix_timestamp, $measurement as $fieldname FROM `get` WHERE bus_id = $busid and cluster_id = $clusid";
$sth = $mysqli->query($sql);
$out = array();
$out['name'] = $fieldname;
while ($rr = $sth->fetch_assoc()) {
$out['data'][] = $rr[$fieldname];
}
array_push($resu,$out);
}
$jsonresult = json_encode($resu);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON(<?php $jsonresult>, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'testchart',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
yAxis: {
title: {
text: ''
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and it won't load either and i tried many ways with that method like put $jsonresult into javascript variable, echoing the json, print the json, print/echo into the getJSON() and still wont work eventhough if i echo the json to a blank space it'll print a json structure that i want.
BUT
if i put the JSON file into getJSON() like this
$(document).ready(function() {
$.getJSON("test.json", function(json)
it will works. but i would not copy paste the json that generated into the json file everytime i would load the charts.
i just wondering why. Any help?
I'm doing the same so in javascript part you have to inclide this:
var json = "<?php echo $pepito; ?>";
datar = JSON.parse(json);
This way you have the data from php in javascript
Also it's important to pass data in array and time in timestamp format multiplied by 1000. for example:
$timestamp=strtotime($fila[0].$fila[1])*1000;
//echo "\n".$timestamp;
$hola[0][]=array( $timestamp, (float)$fila[2]);//RGD
$hola[1][]=array( $timestamp, (float)$fila[3]);//RGA
You have to include the libraries before your script, not sure it's important but you should change it just in case:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
If you have any other quiestion or you need more info let me know.

Ajax dynamic data with column bar chart

Is it possible to run the highcharts column bar charts? I've tried it a couple of times and unfortunately this no real way to refresh the data without reloading it.
I whipped up some pseudo code which is the way I did it at work (I'm not there now so can't get to the code).
Should I whip up a loop and run it like 5,000 times or something with a 5 second delay? I'm not real sure how to proceed.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
< your typical ajax call function here
return some value;
>
$(function () {
<var ajax_far = ajax_function();>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Some Bar'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [ajax_var]
}]
});
});
}, 5000);
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
put your ajax code in one function that it call from ready function...try this
$(document).ready(function(){
example();
setInterval("example()",5000);
}
function example()
{
//ajax code here
}
The ajax call should simply obtain new data for the chart to display. There is no need to redraw the entire chart, you can just replace the series data, or add indivual points. Here is a good article on doing this on the highcharts website here http://docs.highcharts.com/#preprocessing-live-data, but the ajax code they suggest is:
/**
* Request data from the server, add it to the graph and set a timeout to request again.
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // Shift if the series is longer than 2.
// Add the point.
chart.series[0].addPoint(point, true, shift);
// Call it again after one second.
setTimeout(requestData, 1000);
},
cache: false
});
}
In this code, the requestData function is called every second (via setTimout). It obtains a new data point via an ajax call to live-server-data.php and uses chart.series[0].addPoint to add it to the chart.
If the ajax call returned the entire series, you would call chart.series[0].setData to replace the entiire series.
The only thing you need to worry about is making sure the chart is created before you start call addPoint or setData.
$(function () {
var chart;
var list;
$(document).ready(function() {
var options = {
chart: {
//all chart attr here
}
//other attr
}
chart = new Highcharts.Chart(options);
setInterval(function() {
$.ajax({
type: "GET",
url: "service",
dataType: "json",
success: function (data)
{
chart.series[0].setData(data);
}
}),1000); //will set ur data to ajax data every 1 sec
if u want to update to existing chart data try addPoint()
});
});

Categories

Resources