Reputation: 1180
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>
Upvotes: 0
Views: 133
Reputation: 139
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.
Upvotes: 1