Basically I want to query MySQL database using an external PHP script. I want this script to be called every 2 seconds. This 2 seconds interval are initiated with a javascript (jquery, flot), which is as follows:
<script type='text/javascript'>
var data = [];
var dataset;
var totalPoints = 50;
var updateInterval = 1000;
var now = new Date().getTime();
function GetData() {
data.shift();
while (data.length < totalPoints) {
var y;
$.ajax({
url: 'current_api.php',
success: function(currentValue){
y = currentValue;
console.log(y);
},
});
var temp = [now += updateInterval, y];
data.push(temp);
}
}
var options = {
...
}
$(document).ready(function () {
GetData();
dataset = [
{ label: "CURRENT READING", data: data }
];
$.plot($("#flot-line-chart"), dataset, options);
function update() {
GetData();
$.plot($("#flot-line-chart"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
</script>
Currently, Im getting a NULL
value at console.log(y);
. My PHP script (current_api.php
) that handles MySQL queries is as simple as follows:
<?php
require "dbCon.php"; // database credentials
$databaseName = "MAIN";
$tableName = "day"
// OPEN MYSQL DATABASE CONNECTION IN PHP
$dbs = mysql_select_db($databaseName, $con);
// FETCH DATA FROM MYSQL DATABASE
$sql = "SELECT value FROM $tableName ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql);
header('Content-Type: application/json');
while ($row = mysql_fetch_assoc($result)) {
$currentValue = (int) round($row['value']);
}
echo json_encode($currentValue);
// CLOSE THE DB CONNECTION
mysql_close($con);
?>
I'm new with AJAX and does not know if what I'm trying to do is possible. Can someone help me to debug why i'm getting a NULL
value? Thanks in advance.