Is it possible to refresh only the part of the page? How?
the part:
if (checkExpiry($member->expires)==true) {
print timeLeft($leftts);
} else {
print "expired";
}
I have table which is showing name, email, time until membership ends and I need to refresh 'time until membership ends' every second.
You can check out AJAX, where Javascript calls a PHP application of yours an updates only a certain part of the site.
I presume you mean "refresh the page". The answer is not directly. PHP is executed on the server and "normal" HTTP doesn't do server side pushes. This means that once a page is sent to a client, it won't reload unless something or someone on the client asks for it again.
To implement this, you're going to have to, as Ólafur suggested, use some Javascript on the client side to check the timer and then reload the page (or part of it if you prefer) using an AJAX style call.
If you use Javascript, you can do like this:
<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
//time_to_expire.php is called every second to get time from server
var refreshId = setInterval(function()
{
$('#expire').load('time_to_expire.php?userID=<? echo $userID; ?>);
}, 1000);
});
</script>
inside time_to_expire.php you'll put your code to provide the time remaining to expire the user account!
Note that in that example I'm sending a variable "userID" that will contain the user ID for properly retrieve data from the time_to_expire.php file...
Hope it helps or give's you an idea... :)
Related
I want to do something like this: If I am viewing a record and edit it or add a new record and then exit that screen, I should be asked, “Do you want to save?”
How can I develop this thing in php? I haven't done this type of development before..
Any suggestions?
use jquery onbeforeunload function it will be execute when page refresh or
closing browser tab or closing browser .
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
You need to look for changes in javascript. Make a global variable, lets call it changed . Set it to false on page load. Whenever record is edited make it true and whenever it is saved , set it to false. When the user is closing his tab, again which needs to be detected in JS, look for changed variable. If it is true give him a prompt else he can close without any issues.
You will need to javascipt/jquery to listen for the unload event on the window.
I believe you could do something along the lines of:
<script>
function saveAlert() {
var confirm = confirm('You haven\'t saved your form! Do you want to save?');
if (confirm) {
$('form').submit();
}
return confirm;
}
$(function() {
var formSaved = <?=($formSaved) ? 'true' : 'false'?>;
if (!formSaved) {
$( window ).unload(saveAlert());
}
});
All you will need to do is pass a boolean in the $formSaved variable to determine whether the alert needs to be shown or not.
If you wanted to attempt a solution to this question in PHP, you would need to use AJAX to store field data in the database on change/update of fields, without committing the change to the table - you could store it in a cookie or session variable, or in an 'unsaved_records' table of some sort.
If your user navigates to an off-site domain there's nothing you can do in PHP but if they come back to your site, you can alert "you have unsaved data, do you want to continue where you left off?".
You could also wait till they return to the page where they had unsaved data, and restore it to the state it was in, as though they had never left. This would require some careful planning, but it's possible.
Only client side scripting can pause the window or tab being directed to a new location, as is evident in the other answers here.
I am trying to make a chat room on my website, I am using php and mysql to store the messages and all the info. How could I automatically refresh the page every time someone updates the database? example:
If I am on my site, the messages show up on my screen but I can only see more recent messages after I refresh the page. Is there a way to make it real-time?
Also I do not know much javascript/ajax/jquery or any of that. Any help is appreciated!
There will be low amount of traffic on my site. Probably around 10-15 people at a time, if that even.
Your best bet is to make an AJAX request every sec or so and see if there are new messages.
You probably do not want to be reloading the page every time. My recommendation, and there are many ways to do this, is to make a ajax call every so often and check/pull the new information from the database.
I would research AJAX and do a tutorial.
This would be accomplished through ajax by calling a function and updating the div. I would not suggest making people refresh a page everytime they send a message it would get ugly. Another option would be using HTML5 web workers
http://msdn.microsoft.com/en-us/hh549259.aspx
You are going to need to learn AJAX in order to make this work well, and jQuery is probably the easiest way to do it. If we can assume that the DIV you want to update has the ID PonyRides, you would want to do:
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"});
This will get the contents of chat.php and stick it into the #PonyRides DIV. This assumes that chat.php will get the contents of the database and format them into HTML.
The remaining challenge is to make it update whenever your database does, but the simplest way is just to reload the whole chat regardless of whether an update has been made or not.
That will impact performance, but if you have less than a hundred chatters you'll probably be fine. If you have more than that, you'd do well to sense inactivity and decrease the checking period, or only send updates instead of the whole chat. Those are more complicated topics, though, and you can build them in as needed once you get these basic concepts down.
To do this, simply wrap the ajax() call in an interval like so:
setInterval(function(){ //the following code runs repeatedly
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"}); //update our chat div
},5000); //repeat every five seconds
The other, awful method would be to load chat in an iFrame, set to reload periodically using the meta refresh technique. This would be dreadful, and can only be recommended if you are trying for some reason to support incredibly old browsers.
You can use AJAX request to update the values
<script type='text/javascript'>
// function for making an object for making AJAX request
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
function searchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
function useHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
// after doing the stuff, call fn again after 30 s say
setTimeout("searchFabIndia()", 30000);
}
}
}
</script>
<body onload='searchFabIndia();'>
I would suggest making an AJAX request to a file on your server which will update the database. If the update to the database is successful then return the message which was updated. Back on the client side you wait for the response and if you get one then append the message to the end of the content. This way you're loading all the messages every time (which would be expensive), you're only loading new messages.
There must be something similar to SignalR(.net) for php. It lets you add code when an event occurs, I think that is what you are looking for.
Today I am trying to echo this php mysql statement within my javascript code, which commences onclick. However, this php statement seems to run when the page loads on not wait until the onlclick event. Is there any way to solve this? I know that I could use javascript to open other pages and then call back the php statement, but I want this to be light weight.
Thanks!
<script type="text/javascript">
function exitchatfriend() {
document.getElementById("clicktoenteraconversation<?php
echo $otherchatuser ?>").style.display='none';
document.getElementById("chatcontainer").style.display='none';
<?php mysql_query("DELETE FROM currentconversation
WHERE username='$username' and otherchatuser='$otherchatuser'"); ?>
}
</script>
You have a fundamental misunderstanding of the relative roles of PHP and javascript. PHP is a server-side will always execute before the page is sent to the client. This means that the code is never sent to the client, only the results. So if I have:
<?php echo "1+1 is ".(1+1); ?>
the source code that is sent to the client is
1+1 is 2
Javascript, on the other hand, is executed on the client's side. The code is sent to the user's computer, and you expect (hope) that the user's browser correctly interprets the code and does what is being asked. (this is why javascript can't be relied upon for validation, etc, as you can't control what the client does with the code you send them).
If you want an onclick event to run a php script, you must use AJAX (which is basically just javascript executing a new page load in the background and doing something with the result). However, ajax is not super fast (you wouldn't want to run
for(i=0;i<10000;i++){
//some ajax call
}
and you can't rely on it (so if it's super important that this query gets run:
mysql_query("DELETE FROM currentconversation WHERE username='$username' and otherchatuser='$otherchatuser'");
you will want to look for other ways of closing the conversation.
<script type="text/javascript">
function exitchatfriend() {
document.getElementById('clicktoenteraconversation'+ id_of_otherchatuser ).style.display='none';
document.getElementById("chatcontainer").style.display='none';
//A Jquery AJAX Call
var url = "YOUR_SITE_URL/ajax/deleteUser.php";
$.post(url,{" id_of_otherchatuser": id_of_otherchatuser ,"username":username},function(res){
if(res)
{
alert('deleted')
}
});
}
}
</script>
//on the server side /ajax/deleteUser.php
<?php
$otherchatuser=$POST['id_of_otherchatuser'];
$username=$POST['username'];
if(mysql_query("DELETE FROM currentconversation WHERE username='$username' and otherchatuser='$otherchatuser'"))
{
return true;
}
?>
Just to give an idea on concept.
I don't know what it's call. Example
http://search.twitter.com/search?q=%23idontbelieveyou
When you click link above wait a few seconds. Then you will see a notify like this
102 more results since you started searching. Refresh to see them.
There any tutorial for this? Let me know how to make something like that
It's really simple, logically:
A piece of Javascript checks back with the server every n seconds with a timestamp of the latest result it has.
The server checks if any results are available newer than this timestamp and reports back how many there are.
The Javascript displays this notification in the browser.
It would just sent an XHR to the server to see if any more tweets match the query.
If there are new matches, it will return the count and JavaScript updates the DOM to suit.
It is simply polling a script via jquery or Ajax (same thing really)
// Untested, written here without syntax.
var timeSinceUpdate = <?php echo(time()); ?>;
$(document).ready(function(){
setInterval(function(){
$.get('queriesSince.php?searched=idontbelieveyou×inceupdate=' + timeSinceUpdate , function(data){
alert(data);
if(confirm('Add new Data to screen?'))
{
//Add Stuff to DOM and update the timeSinceUpdate from the data recieved.
}
});
}, 3000);
});
I've got a web page that allows to start a certain process and then redirects to another page that displays log file of that process. Since execution takes up to 10 minutes, I want log page to autoupdate itself or load data from the file periodically.
Right now I added
<meta http-equiv="refresh" content="5;url=log.php#bottom" />
to html/head but wondering if there may be a better solution. Can someone give any advice on aproaching this problem?
I do it this way:
var current_length = 0;
function update() {
setTimeout(update, 3000);
$.post("/update_url", { 'current_length': current_length }, function(data) {
if (data.current_length != current_length) return; //it's too old answer
$("#log").html($("#log").html() + data.text);
current_length += data.text.length;
}, "json");
}
update();
The server must skip several bytes at beginning and send json with current_length and the rest of file.
I prefer using memcached to store process output.
You could:
Periodically poll the server to see if there are more messages, basically you would call a PHP script with javascript and would pass the length of the log file in the last poll and then insert into the document the new data. The server would return all the data after that offset and also the new length.
(simpler) Make a long lived PHP script that keeps reading the file and echo and flush it as soon as there's new data. See PHP: How to read a file live that is constantly being written to.
Use AJAX to do this. Easy in jQuery:
<script type="text/javascript">
$(function(){
window.setInterval('updateLog()', 5000);
});
function updateLog() {
$.get('log.php');
}
</script>
Why not use javascript?
Use setInterval and run an AJAX call to log.php periodically.
You could also use an iframe, but the AJAX perdiodical call is a better way of doing it in my opinion.