I'm working on an interface which display data retrieved from my database thanks to a Google Line Chart. However, new data is stored in my database every 10 seconds and I can not refresh the chart automatically.
I need something really basic and I've already looked on the internet. I read something about Javascript/AJAX/JQuery ... but I'm more comfortable with Hardware :D
Here's my files
EDIT : Chart_get and the main file have been modified according to #Michel answer.
fetch.php - Fetch the data and echo
<?php // Connection and Request stuff
$host = blablabla
(...)
$req = $bdd->query('SELECT id, battery FROM Station');
while ($data = $req->fetch()){
$id = addslashes($data['id']);
$charge_batt = intval($data['charge_batt']);
$result .= "['".$id."' , ".$charge_batt."],";
}
$result = substr($result, 0, -1); // Erase the last ","
echo $result;
?>
Output :
['1' , 90],['2' , 89],['3' , 80],['4' , 100],['5' , 90],['6' , 50],['7' , 67]
chart_get.php - Initialize the chart and draw it with the "echo $result" data
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
<?php
echo ("['Date', 'Battery'],");
include('fetch.php');
?>
]);
var options = {
title: 'Battery health',
animation:{
duration: 1000,
easing: 'out',
},
curveType: 'function'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
To refresh the "chart_div" I've tried :
main.html - jQuery script with load function
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<title>Project - Chart</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// first load it once, so it display's the chart
$('#tableHolder').load('chart_get.php');
// then execute the interval
setInterval(function(){$('#tableHolder').load('chart_get.php');}, 5000);
});
</script>
</head>
<body>
<p>Hello</p>
<div id="tableHolder"> </div>
</body>
</html>
But the chart is not displayed at all.
I have absolutely no idea what I'm doing wrong. I am reading in a fast way some tutorials about javascript but if you know how to resolve my issue it would be great to help me :)
Thanks !
Solution from OP.
I've found the answer!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<title>Projet GreenFeed - Station de recharge a energie positive</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
//AJAX Call is compulsory !
var jsonData = $.ajax({
url: "chart_fetch.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Battery',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// First load the chart once
drawChart();
// Set interval to call the drawChart again
setInterval(drawChart, 5000);
});
</script>
</head>
<body>
<div id="chart_div"> </div>
</body>
</html>
First get rid of the <!DOCTYPE>, <html>, <head>, <meta>, <title> tags in chart_get.php.
The data in chart_get.php is the same data you would have in <div id="tableHolder"></div> if you didn't wanted it to refresh.
Second, rewrite your script in main.html to this:
<script type="text/javascript">
$(document).ready(function(){
// first load it once, so it display's the chart
// (otherwise you have to wait 5 seconds)
$('#tableHolder').load('chart_get.php');
// then execute the interval
setInterval(function(){$('#tableHolder').load('chart_get.php');}, 5000);
});
</script>
Related
I am using Google Distance Matrix API for my web application. When I tried loading the map, it shows me an error in the console log. I am new to the API and would appreciate any help. Many thanks! :)
Here is a screenshot of the errors in the console log
Below is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Carpark Demo Code</title>
<!--<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#400;600&display=swap" rel="stylesheet">-->
<style>
</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/json" src="https://maps.googleapis.com/maps/api/distancematrix/json?&key=AIzaSyAvlb7x4ZCfxvpxV90ha3g_YbaYfHPvfvk"></script>
<script>
$(function(){ // ready function
displayLiveData();
googleDistanceCalc();
});
function displayLiveData(){ // 1st Function - carpark details, address
$.ajax({
type: "GET",
url: 'https://maps.googleapis.com/maps/api/distancematrix/json?&key=AIzaSyAvlb7x4ZCfxvpxV90ha3g_YbaYfHPvfvk',
dataType: 'json'
})
.done(function(json) { /* same as ready function, when data finishes loading and do something after */
console.log("Successfully Loaded!");
})
.fail(function() {
console.log("Loading Error.");
});
}
</script>
</body>
</html>
Thanks for the help!
I am having a problem to show different types of graphs in different divs using Javascript and JQuery in a HTML file.
I am using a single PHP file that generates those graphs according to the parameters I pass it through the URL (GET Method). The PHP files imports the data from a PostgreSQL database and creates the graphs using FLOT Library.
After loading the page I want to show the graphs, and after 1 minute, I want to refresh each graph, I am using JQuery to achieve this.
If I use only one div showing only one graph it works just fine, it show the graph and refreshes it.
The problem is when I try to load different graphs in different divs because it only shows the initial graph in the first div only, and then it goes refreshing and showing the other graphs but in the same div # 1.
Can someone give an idea how to solve it? or tell me what is wrong in the code?
This is the code I'm using:
<html>
<head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
function update()
{
$('#flot1').load('basic.php?p=1&c1=00b8d8&c2=eff9fb');
$('#flot2').load('basic.php?p=2&c1=8be3b8&c2=f1fbf6');
}
setInterval( "update()", 60000 );
</script>
</head>
<body>
<div id = "flot1"></div>
<div id = "flot2"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#flot1").load('basic.php?p=1&c1=00b8d8&c2=eff9fb');
$("#flot2").load('basic.php?p=2&c1=8be3b8&c2=f1fbf6');
});
</script>
</body>
</html>
This is the code of the PHP file that creates the graphs:
<html>
<head>
<script language="javascript" type="text/javascript" src="flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="flot/jquery.flot.js"></script>
</head>
<body>
<div id="placeholder" style="width:202px;height:140px;"></div>
<?php
include "opendb.php";
if(!isset($tag)){ $tag=$_GET['p']; }
if(!isset($c1)) { $c1="#".$_GET['c1']; }
if(!isset($c2)) { $c2="#".$_GET['c2']; }
$dataset1 = array();
$query1="SELECT nu_valor, nu_fecha_hora_timestamp FROM x001t_historico_tag WHERE co_tag = '$tag' ORDER BY nu_fecha_hora_timestamp DESC LIMIT 6";
$result1 = pg_query($query1);
while ($row = pg_fetch_array($result1))
{
$unix = $row['nu_fecha_hora_timestamp'];
$nu_valor = $row['nu_valor'];
$dataset1[] = array( $unix, $nu_valor );
}
?>
<script type="text/javascript">
var dataset1 = <?php echo json_encode($dataset1); ?>;
$(function () {
var options = { xaxis: { ticks: [] }, yaxis: { ticks: [], autoscaleMargin: 0.5 }, grid: { backgroundColor: '#fff', color: "#fff" },
};
//plotting
$.plot($("#placeholder"),[
{
color: '<?php echo $c1; ?>', data: dataset1 ,
lines: { show: true, fill: true, fillColor: "<?php echo $c2; ?>", lineWidth: 2},
} ], options);
});
</script>
</body>
</html>
If I run the graph from the browser passing it the parameters through the URL it also works fine and creates the graph.
i used google translator for textbox. its working as excepted but when i moved to production it's showing
"The page at 'https://myexample.org/' was loaded over HTTPS, but requested an insecure script
'http://www.google.com/inputtools/request?text=kamla&ime=transliteration_en_ta&num=5&cp=0&cs=0&ie=utf-8&oe=utf-8&app=jsapi&uv&cb=_callbacks_._0je9phncp'.
This request has been blocked;"
so how to convert translator url http to https and my code is:
<!DOCTYPE html>
<html>
<head>
<title> Transliteration Help </title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("elements", "1", {packages: "transliteration"});
</script>
<style>
.inputapi-transliterate-indic-suggestion-menu{
z-index: 100;
}
</style>
<script>
function OnLoad() {
var currValue = document.getElementById("txtTranslator");
var options = {
sourceLanguage:
google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage:
[google.elements.transliteration.LanguageCode.TAMIL],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
var control = new
google.elements.transliteration.TransliterationControl(options);
control.makeTransliteratable(["txtTranslator"]);
var postValue = document.getElementById("txtTranslator");
} //end onLoad function
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body>
<input size="40" type="text" id="txtTranslator"/>
</body>
</html>
Open the https://www.google.com/jsapi and copy paste the code locally.
Change the URL's with http to https.Include this file in your code.
Also remove this code if you're using it
/* google.load("elements", "1", {
packages: "transliteration"
}); */
i am try to get latitude and longitude value from ip address
after getting lat and lng value POST in to php file using AJAX and generate new xml file
this is my html file:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function getlg(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
$.ajax({
type: "POST",
url: "http://localhost/SVN/trunk/home/url.php?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val(),
contentType: "text/html",
success: function(token) {
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
}
</script>
<body>
<div id="region"><h5></h5></div>
Enter Radius: <input type="text" id="radius1"></input>
<input type="button" id="filter"onclick="getlg()" value="Go">
</body>
</head>
</html>
this is my php file:-
<?php
function convertNodeValueChars($node) {
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType == XML_TEXT_NODE) {
$childNode->nodeValue = iconv('utf-8', 'ascii//TRANSLIT', $childNode->nodeValue);
}
convertNodeValueChars($childNode);
}
}
}
$url='http://services.gisgraphy.com/geoloc/search?lat='.$_GET['lat'].'&lng='.$_GET['lng'].'&radius='.$_GET['radius'];
$doc = new DOMDocument();
$doc->load($url);
$doc->save('General.xml');
?>
in this file i am try to Get lat and long and radius from html ajax function and getting one new xml file with help of url.
but its take so much time if radius is biggest.
i want to try this php code in java script dont like server side scripting.
please help me out with this...
thanks...
try this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
var location = "http://services.gisgraphy.com/geoloc/search?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val();
document.write('Link text');
}
</script>
<body>
<div id="region"><h5></h5></div>
<input type="text" id="radius1" onchange="myFunction()"></input>
</body>
</head>
I have searched a lot and finally able to run my google charts code. Here is my code using both data view and data table.
//Here is my code for chartDraw.php
<html>
<head>
<!--Load the AJAX API -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function drawChart(){
var jsonData = $.ajax({
url:"getdata.php",
dataType:"json",
async:false
}).responseText;
//This is used when you hard code your values: static data. Here I am taking data from database so commented it.
/*var jsonData='{"cols":[{"label":"User ID","type":"string"},{"label":"Group Name","type":"string"},{"label":"Requested Nodes","type":"number"},{"label":"Actual PE","type":"number"}],"rows":[{"c":[{"v":"user 1"},{"v":"ufhpc"},{"v":1},{"v":5.000}]},{"c":[{"v":"user2"},{"v":"ufhpc"},{"v":1},{"v":7.000}]}]}';
*/
//Create our data table out of JSON data loaded from server
var data=new google.visualization.DataTable(jsonData);
//PieCharts expects 2 columns of data: a label and a value, so we need to use a DataView to restrict to 2 columns
var view=new google.visualization.DataView(data);
view.setColumns([0,3]);
//Instantiate and draw our chart, passing in some options
var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(view,{width:400,height:240});
}
//Load the visualization API and the piechart package
google.load('visualization','1',{'packages':['corechart']});
//Set a callback to run when the google visualization API is loaded
google.setOnLoadCallback(drawChart);
</script>
</head>
<body>
<!--Div that will hold the pie chart -->
<div id="chart_div"></div>
</body>
</html>
//getdata.php: contains connections and query
<?php
mysql_connect('localhost','user','password');
mysql_select_db('dbname');
$sqlquery1="select userid,group_name,req_nodes,actualPE from jobs where userid='zhang' limit 200";
$sqlresult1=mysql_query($sqlquery1);
$table=array();
$table['cols']=array(
array('label'=> 'User ID', type=>'string'),
array('label'=>'Group Name', type=>'string'),
array('label'=>'Requested Nodes', type=>'number'),
array('label'=>'Actual PE', type=>'number')
);
$rows=array();
while($r=mysql_fetch_assoc($sqlresult1)){
$temp=array();
$temp[]=array('v' => $r['userid']);
$temp[]=array('v' => $r['group_name']);
$temp[]=array('v' =>(int) $r['req_nodes']);
$temp[]=array('v' =>(float) $r['actualPE']);
$rows[]=array('c' => $temp);
}
$table['rows']=$rows;
$jsonTable = json_encode($table);
//this print statement just for testing
print $jsonTable;
?>
What is the difference between DataView class and DataTable constructor?
If I don't use DataView, it doesn't print.
Use google:
Google visualization API.
Stack overflow is not for tutorials, it is for productive questions. If you would like to create tutorials you might want to use a website called The Code Player.