I am gathering live data from a mysql database using php and ajax. I want the data to be live updated every 2 seconds.
My code displays the chart and data as I want it, but does not live update the data from the database. The piece of code meant to be doing that is:
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
And I think the error lies somewhere there as when I inspect the element with google chrome it tells me "Uncaught TypeError: Cannot read property 'reload' of undefined".
Here is the full JS code:
<script type="text/javascript">
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "php/connection3_temp.php",
dataType:"json",
async: true
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Ambient Temp.');
data.addColumn('number', 'Object Temp.');
data.addColumn('number', 'Humidity');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.amb_temp),
parseFloat(row.obj_temp),
parseFloat(row.hum)
]);
});
var options = {
title: 'Temperature and Humidity against Time',
legend: { position: 'bottom' },
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 0},
2: {targetAxisIndex: 1}
},
vAxes: {0: {title: 'Temp. (°C)',
minValue: 0,
maxValue: 30
},
1: {title: 'Humidity (%)',
minValue: 20,
maxValue: 80
}
},
hAxis: {
title: 'Time (s)'
},
};
var chart = new google.visualization.LineChart($('#temp_chart').get(0));
chart.draw(data, options);
});
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
}
</script>
and also the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "raspberryblue";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM sensortag3 ORDER BY id DESC LIMIT 3000";
$result = $conn->query($sql);
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysqli_error() . "<br>";
$message .= 'Whole query: ' . $sql;
die( $message );
}
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "timestamp": "' . $row['timestamp'] . '",' . "\n";
echo ' "amb_temp": "' . $row['amb_temp'] . '",' . "\n";
echo ' "obj_temp": "' . $row['obj_temp'] . '",' . "\n";
echo ' "hum": "' . $row['hum'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
$conn->close();
?>
There's no property named reload() in your script. That's why the console is showing undefined property reload(). So add the reload method inside ajax() for refreshing the data.
Related
I am trying to us Ajax to call a php script which gets data from my PostgreSQL In php, my code is:
<?php
# Includes
require("database.inc.php");
require("json.inc.php");
# Retrive URL arguments
$table = $_REQUEST['table'];
$fields = isset($_REQUEST['fields']) ? $_REQUEST['fields'] : '*';
$parameters = isset($_REQUEST['parameters']) ? " where " . $_REQUEST['parameters'] : '';
$order = isset($_REQUEST['order']) ? " order by " . $_REQUEST['order'] : '';
$limit = isset($_REQUEST['limit']) ? " limit " . $_REQUEST['limit'] : '';
# Perform the query
$sql = "select " . $fields . " from " . $table . $parameters . $order . $limit;
$db = pgConnection();
$statement=$db->prepare( $sql );
$statement->execute();
# send JSON or JSONP results
sendJSON($statement);
?>
and here is my Ajax:
$.ajax({
url: "ws_geo_attributequery.php",
//table:'address',
//fields:'file_as_na',
type:'GET',
dataType: "jsonp",
data: {
'table:':'address',
'fields':'file_as_na',
id: 1
},
success: function(response){
var data = $(response).map(function(){
return {value: this.file_as_na, id: this.id};
}).get();
$('#name').autocomplete({
source: data,
minLength: 0,
select: function(event,ui){
$('input#id').val(ui.item.id);
}
});
}
});
I am not getting any result from my Db. I am sure the Problem in my ajax request.
I do appreciate any help.
I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}
When I'm using select2 with my database on localhost. It works correctly.
But when I'm using with database on server, eg 10.0.0.1 it doesn't work.
Here's my select2 script :
$('#slDrug').select2({
placeholder: 'ค้นหาเวชภัณฑ์',
minimumInputLength: 1,
allowClear: true,
language: "th",
ajax: {
url: 'ajax/drugSearch.php',
dataType: 'JSON',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
query: term,
start: page,
stop: 20
};
}, results: function (data, page) {
var more = (page * 10) < data.total;
return { results: data.rows, more: more };
}
}, id: function(data) {
return { id: data.code }
}, formatResult: function(data) {
return '[ ' + data.code + ' ] ' + data.name + ' ความแรง : ' + data.strength + ' หน่วยนับ : ' + data.units;
}, formatSelection: function(data) {
return data.code + ' ' + data.name + ' ' + data.strength;
}
});
And here's my php code :
<?php
require_once('../require/medoo.min.php');
// Select connectinfo from database
$localDB = new medoo();
$getHosInfo = $localDB->select("sys_config","*");
foreach($getHosInfo as $g){
$host = $g['host'];
$user = $g['user'];
$pass = $g['password'];
$dbname = $g['dbname'];
}
header('Content-type: text/html; charset=utf-8');
$dsn = 'mysql:host='.$host.'; dbname='.$dbname.'; charset=utf8';
try {
$conn = new PDO( $dsn, $user, $pass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = $_GET['query'];
$callback = $_GET['callback'];
$start = $_GET['start'];
$stop = $_GET['stop'];
$start = empty($start) ? 1 : $start;
$stop = empty($stop) ? 10 : $stop;
$start = ($start - 1) * $stop;
$sql_total = 'select count(*) as total from drugitems where name like "%' . $query . '%"';
$st = $conn->prepare($sql_total);
$st->execute();
$rows_total = $st->fetch();
$sql_rows = 'select icode, name, strength,units,unitcost,unitprice,did,antibiotic,fp_drug
from drugitems
where name like "%' . $query . '%" limit ' . $start . ', ' . $stop;
$st = $conn->prepare($sql_rows);
$st->execute();
$rows_result = $st->fetchAll();
$data = array();
foreach($rows_result as $r)
{
$obj = new stdClass();
$obj->code = $r['icode'];
$obj->name = $r['name'];
$obj->strength = $r['strength'];
$obj->did = $r['did'];
$obj->unitprice = $r['unitprice'];
$obj->unitcost = $r['unitcost'];
$obj->units = $r['units'];
$obj->antibiotic = $r['antibiotic'];
$obj->fp_drug = $r['fp_drug'];
$data[] = $obj;
}
$json = '{"ok": 1, "total": ' . $rows_total['total'] . ', "rows": ' . json_encode($data) . '}';
echo $callback . '(' . $json . ')';
?>
I can generate now highcharts calling data with mysql. Now I plot splines, but I need to combine 2 splines (for TMax and TMin) and 1 column (for Rain). Anybody knows what I should change in the next two files, I guess in index.php ? I can do plot this combination using csv files but now with mysql. Any idea?
Code of mysql-highcharts.php
<?php
session_start();
$con = mysqli_connect("xxxx","xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_set_charset($con, 'utf8');
function split($date){
$day=substr($date,0,2);
$month=substr($date,3,2);
$year=substr($date,6,4);
return $year . "/" . $month . "/" . $day;
}
$sth = mysqli_query($con,"SELECT City,TMax FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows = array();
$rows['name'] = 'TMAX';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['TMax'];
}
$sth = mysqli_query($con,"SELECT City,TMin FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows1 = array();
$rows1['name'] = 'TMIN';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
$sth = mysqli_query($con,"SELECT City,Rain FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Data");
$rows2 = array();
$rows2['name'] = 'RAINS';
while($rr = mysqli_fetch_assoc($sth)) {
$rows2['data'][] = $rr['Rain'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Code of index.php (highcharts code)
<!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.7.1/jquery.min.js"></script>
<script type="text/javascript">
<?php
$city = $_POST["City"];
session_start();
$_SESSION['City'] = $_POST['City'];
$_SESSION['date8'] = $_POST['date8'];
$_SESSION['date9'] = $_POST['date9'];
?>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql-highcharts.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'TMax-TMin-Rain <?php echo $city ?>',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Temperature (ºC)'
},
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>
Simply set for that specific series type, like this:
$rows1 = array();
$rows1['name'] = 'TMIN';
$rows1['type'] = 'column';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
I would like to know what is the latest JQuery syntax for parsing a JSON response by array index from a HTTP GET or POST request. My server side works great so I am look for way to parse the table row returned by PHP.
Here is my SERVER SIDE PHP code:
function qry_select_account($pk_account) {
// Global variables
Global $db_host, $db_user, $db_pass, $db_name;
// Connect to database server
$dbc = mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
// Select target database
mysql_select_db($db_name) or die(mysql_error());
// suchislife801 <--- Selects account information
// Run query
$sql_qry = mysql_query("SELECT * FROM tblaccount
WHERE pk_account = '$pk_account'") or die(mysql_error());
// SQL Criteria AND acc_confirmed = 'y' AND acc_locked = 'n'
// Fetch table row for this user
$row = mysql_fetch_row($sql_qry);
print json_encode($row);
//echo 'Account: ' . $row[0];
//echo '<br />';
//echo 'Passowrd: ' . $row[1];
//echo '<br />';
//echo 'Acc Level: ' . $row[2];
//echo '<br />';
//echo 'Email: ' . $row[3];
//echo '<br />';
//echo 'Language: ' . $row[4];
//echo '<br />';
//echo 'Time Zone: ' . $row[5];
//echo '<br />';
//echo 'Signup: ' . $row[6];
//echo '<br />';
//echo 'Conf Code: ' . $row[7];
//echo '<br />';
//echo 'Confirmed: ' . $row[8];
//echo '<br />';
//echo 'Locked: ' . $row[9];
mysql_free_result($sql_qry);
// Close Connection
mysql_close($dbc);
}
Here is my JQuery code which is not working.
<script type="text/javascript">
$(function(){
$('#test_btn').live('click', function() {
$.getJSON("http://localhost/api.php?call=select_account&p0=suchislife801", function(json){
alert("JSON Data: " + json);
});
});
</script>
You can use jQuery.parseJSON( json ) function.
Make sure that json returned from server is a valid json
You can validate json response from here
Use following to check if error is returned by server
$.getJSON("example.json", function(data) {
alert(date);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
);
looping through json depends on type of json
if its a map type structure, like following
var map = {
"data1": "value1",
"data2": "value2"
};
you can use following to iterate through
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
Reference: http://api.jquery.com/jQuery.each/