I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..
My php -
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer <= 0){
}else{
echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
echo '<div id="user">#'.$user.'</div>';
echo '<div id="timer">'.$timer.' </div>';
}
}
}
I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.
As per my comment, you could do something like this:
Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
Create php script which returns new $timer whenever it's called:
ajax-timer.php
<?php
/* include file where $conn is defined */
$response = array();
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer > 0) {
//Add just timer to response array
$response[] = $timer;
}
}
}
//Return json response and handle it later in ajax:
echo json_encode(array(
'result'=>empty($response) ? 0 : 1,
'data'=>$response));
die();
Request data from ajax-timer.php with $.ajax and populate data when response is received:
timer-update.js
var ajaxTimerThread = 0;
var ajaxTimerRunning = false;
function ajaxTimerRun() {
//Prevent running function more than once at a time.
if(ajaxTimerRunning)
return;
ajaxTimerRunning = true;
$.post('ajax-timer.php', {}, function (response) {
ajaxTimerRunning = false;
try {
//Try to parse JSON response
response = $.parseJSON(response);
if (response.result == 1) {
//We got timer data in response.data.
for(var i = 0; i < response.data.length; i++) {
var $timer = $('.timer').eq(i);
if($timer.length) {
$timer.html(response.data[i]);
}
}
}
else {
//Request was successful, but there's no timer data found.
//do nothing
}
//Run again
ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
}
catch (ex) {
//Could not parse JSON? Something's wrong:
console.log(ex);
}
});
}
$(document).ready(function() {
// Start update on page load.
ajaxTimerRun();
})
Toss your existing php code into a separate .php file
Then use a jquery method called load() to load that php file into your div.
$(document).ready(function() {
$("#div_ID_you_want_to_load_into").load("your_php_file.php");
var pollFrequency = function() {
if (document.hidden) {
return;
}
$("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
};
setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});
Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.
Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.
Related
I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");
I have a block of jQuery which uses the $.get() method in a setInterval(). I don't understand how to get data from the second URL to the jQuery code.
Jquery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.getJSON("check_time.php", function(update) {
if (update) {
$("#slideshow").load("phppage.php");
}
});
}, 600000);
</script>
PHP - check_time.php
<?php
require_once('connect_pdo.php');
header('Content-type: application/json');
$stmt = $conn->prepare("$sqlst = $conn->prepare("SELECT COUNT(*) AS count
FROM ads
WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$sqlst->execute();
$row = $sqlst->fetch();");
$stmt ->execute();
$row = $stmt ->fetch();
$update = $row['count'] > 0;
$updtstatus = json_encode($update);
echo "$updtstatus";
?>
I am not getting the variable from check_time.php to the update variable in function(update).
Small alter in php page
$updtstatus = json_encode(array('count'=>$update));
echo $updtstatus;
Now your JSON is in fact something like this {"count":"true"}.
So change your if statement slightly.
$.getJSON("check_time.php", function(update) {
if (update.count===true) {
$("#slideshow").load("phppage.php");
} else {
console.log("No results");
}
});
This fiddle simulates the above answer
Your jQuery functions expects data to be returned in JSON format, so simply do so :) I've also found some flaws within your PHP code. This should do the trick:
$.get('check_time.php', function(data) {
console.log(data); // Console logging is always good
if (data.status) {
alert('Load slideshow');
}
});
check_time.php
<?php
require_once('connect_pdo.php');
$json = []; // The JSON array which will be returned
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM ads WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$stmt->execute();
$json['status'] = (bool) $stmt->rowCount(); // Status is either false (0) or true (> 0)
echo json_encode($json);
I have an index.php page. The function of this page is infinite scrolling using AJAX, PHP and MySQL. The top portion contains PHP MySQL codes and bottom contains JavaScript.
I want to print the total number of rows in center of the page, but every time I try it shows "undefined variable" error.
I think when loading the page, the total number of variable tries to print first and then the PHP query takes place, so it shows "undefined variable", but when I put the total number of variable inside the PHP codings, there is no problem.
How can I prevent this?
My index.php is
//my php part here
<?php
if(isset($_POST["anotherID"])){
require_once("config.php");
$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%' ORDER BY rand() LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
$count = $actual_row_count;
exit;
}
?>
//my html part here
<html>
//some html codes
<?php echo $count; ?>
//some html codes here
//my java scripts here
<script type="text/javascript">
var busy = false;
var limit = 6
var offset = 0;
var anotherID = 5
function displayRecords(lim, off) {
$.ajax({
type: "POST",
async: false,
data: "limit=" + lim + "&offset="+ off+"&anotherID="+anotherID,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button"><div id="loader_image"><img src="loader.gif" alt="" width="24" height="24">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
//some html codes her
</html>
I know when a page is loading, the HTML parts are first loaded and then my jQuery stimulates the PHP part and then my results appear.
How can I fix this?
Why does $count always show "undefined variable"?
Thanks in advance.
You get an error of undefined $count because $count is defined only inside the if statement.
When the if clause doesn't apply $count is not defined.
Add an else clause to the if and initialize $count=0; and it will solve your problem.
Example:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>
I'm making a chatbox for my website but when I try to get a data- value my result is undefined. My javascript calls the AJAX to my fetchChat.php as so...
var myVar = setInterval(function () {refreshChat()}, 5000);
function refreshChat() {
var lastItem = 0;
lastItem = $(".chatmessage:last-child").data('value');
if (typeof lastItem === 'undefined')
{
alert("undefined");
lastItem = 0;
}
$.post("outputPages/fetchChat.php", {'li':lastItem}, function(response)
{
$(".messagefeed").append(response);
});
}
And my PHP in fetchChat is:
<?PHP
require "../pages/connect.php";
$li = $_POST;
$li = implode($li);
$fetch = "SELECT * FROM chat WHERE messageID >= '$li' ORDER BY messageID ";
if ($result = $mysqli->query($fetch)) {
while ($row = $result->fetch_array()) {
$ID = $row['messageID'];
$date = $row['messageDate'];
$persona = $row['messagePersona'];
$message = htmlspecialchars($row['message'], ENT_QUOTES);
echo "<p class='chatmessage' data-value='$ID'>$date $persona: $message</p>";
}
}
?>
So basically I use the data-value of the last message to get all messages greater than the last message. But whenever I echo lastItem in javascript it returns undefined. Any help is really appreciated! This is my own idea and Im trying to see what I can do with my school knowledge so far.
Fixed! I have to change my lastItem to $(".chatmessage:last-child").attr('data-value');
Thank you Roumelis for the help!