Refreshing php page without reloading content? - javascript

I've searched everywhere for a method where a page can reload automatically for every x seconds without actually reloading the page's contents, I have php code(includes some html) which updates my database table whenever a new user joins the page. However this only works once.
PHP CODE
<?php
$userOn5 = "SELECT * FROM `usersOn` WHERE name = '$username'";
$query4 = mysql_query($userOn5) or die (mysql_error());
while ($row = mysql_fetch_array($query4)) {
// Gather all $row values into local variables for easier usage in output
$timenow = $row["time"];
}
$user = "SELECT * FROM `user`";
$query3 = mysql_query($user) or die (mysql_error());
while ($row = mysql_fetch_array($query3)) {
$usernow = $row["name"];
}
$secs = time() - $timenow;
mysql_query("UPDATE user SET name = '$user'");
if ($username == $usernow) {
?>
<div id="container" style="display:none;">
I've attempted using meta tag but that reloads the entire content, I've attempted moving the entire php code to a separate php file and tried loading it inside a div called 'show' in the page:
var auto_refresh = setInterval(
function ()
{
$('#show').load('registeruser.php').fadeIn("slow");
}, 10000); // autorefresh the content of the div after
//every 10000 milliseconds(10sec)
Basically what I'm trying to do is rerun the php code every 10 seconds. Help?

Quite likely your issue is due to browser cache. You can use the following workaround -- that's actually what ajax does when you use cache: false:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t);
$('#container').fadeIn("slow");
}, 10000);
});
UPDATE
Alternatively, you can use the following:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t).find('> div').fadeIn("slow");
}, 10000);
});

Related

Refresh <a> that has PHP variable connected to XML URL without reloading

I have two files home.php and calc.php, the file calc.php has variables parsing from XML URL and this url data keep changing automatically but the problem is i need a specific element in this home.php keep refreshing automatically
as you see in my code there is a div has alink inside it and the link has php variable $amount and this var keep updating,
so i tried to use AJAX like this but it did not work and after 1 s the link disapear So what to do please?
THANKS
var auto_refresh = setInterval(
function () {
$('#low2z3').load('calc.php'});
}, 1000);
<div id="linnnez4" class="linnne res1"><a id="low2z3"><?php echo $amount1;?></a> </div>
<!--in calc.php-->
<?php
$url = 'http://magneticexchange.com/export.xml';
$xml = simplexml_load_file($url);
foreach($xml->item as $item) {
if($item->from == "PRUSD" && $item->to == "NTLRUSD") {
$give = $item->in;
$get = $item->out;
$amount = 10;
$give1 = $amount." ".$item->from;
$get1 = $amount * $get / $give;
$get2 = number_format($get1, 2). " ".$item->to;
$amount1 = $item->amount;
break;
}
}
?>

Scroll to bottom of item on Ajax load

I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details

Javascript timer refresh and php function [duplicate]

I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);
It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation

PHP/JS Unlimited scroll loading all data from MySQL in one scroll

I was working on Unlimited scroll for my website using PHP and JavaScript. I almost made it but there was a problem In my code, after scrolling to the bottom of the page my script should load 15 articles every time I scroll to the bottom and after its done It stops loading more posts, but instead it loads all of the articles and then stops the script when all of the posts are loaded.
My JavaScript code:
<script>
// Unlimited Scroll
$(document).ready(function() {
$('.post-load').hide();
var load = 0;
var nbr = "<?php echo mysql_num_rows($sql); ?>";
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('.post-load').show();
load++;
if (load * 15 > nbr) {
$('.post-load').hide();
} else {
$.post("extensions/ajax.php", {
load: load
}, function(data) {
$('.lb').append(data);
$('.post-load').hide();
});
}
}
});
});
extensions/ajax.php File for loading the posts through PHP:
<?php
include 'connect.php';
$load = htmlentities(strip_tags($_POST['load'])) * 2;
$sql = mysql_query("SELECT * FROM articles ORDER BY postNum DESC");
$countBlop = mysql_num_rows($sql);
$queryL = mysql_query("SELECT * FROM articles ORDER BY postNum DESC LIMIT 15,".$countBlop."");
while ($posts = mysql_fetch_assoc($queryL)) {
?>
<div class="article">Echo the posts...</div>
<?php } ?>
Looks to me like your LIMIT syntax is backwards
LIMIT 15,".$countBlop.
should be
LIMIT ".$lastIndex.",15
As is now it would be starting at record 15 and then continuing to load until you reach the total count(as defined by $countBlop)
You will also need to have a way for jQuery to pass the last index to the ajax call.

Constantly redirecting after n seconds

I have a list of urls that I would like to open in a popup for say 10 seconds. So I click a button and it will open the first url then wait 10 seconds and play the next and so on until it's over.
I have found a few functions that I thought would work or help and I thought my logic was right and thought it should work but maybe someone with more knowledge can help me out. This is what I have:
<script type="text/javascript">
function Redirect(url) {
popupWindow = window.open(
url,'popUpWindow','height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no')
}
function newPopup() {
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
<?php
}
?>
}
</script>
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
?>
<script type="text/javascript">
function Redirect(url) {
window.open(url, 'popUpWindow', 'height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
}
function newPopup() {
<?php
$stmt = $db->query("SELECT * FROM `songs`");
$songs = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($songs AS $index => $song) {
printf("setTimeout(Redirect('http://www.youtube.com/embed%s?autoplay=1'), 4000);", $song->url);
}
?>
}
// Start
newPopup();
</script>
Change
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
to
setTimeout(function() {
Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")}, 4000);
would be a good start
I would do it like this:
var data = [];
var current = 0;
<?php
while($jsRow = mysql_fetch_array($jsSql))
echo "data.push($jsRow['url']);";
?>
function Redirect()
{
}
function newPopup()
{
Redirect(data[current]);
current++;
if (current < data.length)
setTimeout(function(){newPopup();}, 10*1000)
}
All you have to do is to call newPopup for the first time on some event. You mention button click.
The code also check if there are no more items to play.
The key to this issue is that after you open the popup window with the first URL, you then want to just set the window.location on the existing popup window so that it just loads a new URL. So, it would be something like this:
// globals
var songList;
function openNewPopup(url) {
return window.open(url, 'popUpWindow','height=481,width=858,left=10,top=10,
resizable=no,scrollbars=no,toolbar=no,menubar=no,
location=no,directories=no,status=no');
}
Then, for subsequent page loads into that existing popup window, you just
function setNewPopupURL(url, popup) {
popup.location = url;
}
I don't really know PHP, but you'd want to put the list of songs into a JS variable that you can later loop over:
// populate the songList
// the goal here is to do songList.push(songURL) for each song
// to add them all to the songList
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
songList.push("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>");
<?php
}
?>
And, then you can start the popup rotation by calling a function like this:
function runPopup() {
var index = 0;
var popup = openNewPopup(songList[index++]);
function next() {
setNewPopupURL(songList[index % songList.length), popup);
++index;
setTimeout(next, 10*1000);
}
setTimeout(next, 10*1000);
}

Categories

Resources