I'm trying to UPDATE my php page every 5 seconds so the new data can come in into a .json file, so basically what it does, is, it gets the data from the database, and creates a .json file with this data, I need this php file to update every 5 seconds, so the .json file is updating too.
The code (JsonfileAPI.php):
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "nps";
$dBUsername = "nps";
$dBPassword = "nps";
$dBname = "nps";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword,
$dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "JsonfileAPI.php",
type: 'post',
dataType: 'json',
success: function(response) {
$('.time').html(response);
}
});
}, 5000);
});
</script>
You can use this code in your application, I suggest to use separate files like index.php (for your html code) and action.php for PHP script. and don`t need .json file.
Try this, in index.php html part and javascript part like this
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "action.php",
type: 'post',
// dataType: 'json',
success: function(response) {
console.log(response);
$('.time').html(response);
}
});
}, 5000);
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="time">
</div>
</body>
</html>
Then your action.php file should be like this,
<?php
$localhost = "nps";
$username = "nps";
$password = "nps";
$dbname = "nps";
// db connection
$connect = new mysqli($localhost, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("Connection Failed : " . $connect->connect_error);
} else {
// echo "Successfully connected".$dbname;
}
$sql = "SELECT * FROM dados";
$result = $connect->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$output['data'][] = array(
$row[0],
$row[1],
$row[2]
);
}
}
$connect->close();
echo json_encode($output);
I have checked and it work fine. Think it will be help.
Related
I'm going to use the real-time temperature values stored in MariaDB server to show real-time graphs on the web.
(Temperature values continue to accumulate in real time once every 5 seconds.)
Through a lot of trial and error, I decided that Highcharts.js would be the best tool for drawing graphs.
https://www.highcharts.com/stock/demo/dynamic-update
The link above is the demo source I used.
What I've been trying to do in the most
I've been putting a lot of things into the bar y.
I tried various things in the data.push of series.
(I'm a beginner on coding......)
I didn't know what I typed wrong, so I entered everything. I'm sorry.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script type="text/javascript"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script>
Highcharts.stockChart('container', {
chart: {
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
$(document).ready(function() {
var url = "https://---include json---.php";
$.getJSON(url, function(json) {
var val= json;
var temp1=(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
console.log(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
})});
var x = (new Date()).getTime() // current time
var y = temp1;
Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);//연속
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'TEST test'
},
exporting: {
enabled: true
},
credits:{
enabled:false
},
series: [
{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
y;
for (i = -999; i <= 0; i += 1) {
data.push([
//time + i * 1000,
//Math.round(Math.random() * 100)
]);
}
return data;
}())
}]
});
</script>
The following php code is the php code for json data.
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$temp = array();
$temp["temp1"] = $row["temp1"];
array_push($response["temp"], $temp);
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>
The above code values are output as shown below.
{"temp":[
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.82},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":18.05},{"temp1":17.93},{"temp1":17.82},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.82},{"temp1":18.05},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93}
]}
If you run the code, the graph won't appear on the screen.
I don't know how to print out json's value on the graph.
I translated it using Google translation because I am not good at English. I would like to thank you all for your reply.
Add a content type to the header:
<?php
header("Content-type: application/json; charset=utf-8");
You can use chart.js library. Simple and powerful
https://www.chartjs.org
Here are some example how to use:
https://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/
First of all: Wellcome to SO :)
I think you have the wrong Dataformat for your Data. You have a Array of Objects
[{"temp1":17.93},....]
But the example say:
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
An Array of Array. Try this:
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$response["temp"][] = array("temp1", $row["temp1"]); // <-- change this line
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>
I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>
I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$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 ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});
I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');