How can I print text to a webpage every second? - php

I want to make a website write a message every second.
<?php echo '111';?>
How can do this?

If you want the user to see a message every second in their browser, this isn't doable in PHP. PHP is a server-side language, meaning that by the time the page reaches the browser, PHP's work is done.
You'll need a client-side language such as Javascript to accomplish this, using something like setTimeout: http://www.w3schools.com/jsref/met_win_settimeout.asp
Edit after OP's clarification:
If instead what you want is to execute the script once every X seconds, then you should look into cron. You can use cron to schedule your script to run as often as you desire.
So an example of how it might work is:
You write a script that sends an email once
You set your crontab to execute your script, say, once every hour
Every hour, cron will execute your script, sending you an email

You cannot really do it with PHP. Instead, this would be accomplished with Javascript. If the message to be displayed must be supplied by the server, it complicates things significantly, requiring AJAX transactions. However, if the messages are predefined or can be calculated on the fly, it is fairly straightforward:
<div id='someId'>Message will go here</div>
<script type='text/javascript'>
var textSpace = document.getElementById('someId').innerHTML;
var refreshTimeout = setInterval(function() {
// every second, add another ' message' into the element
textSpace = textSpace + ' message';
}, 1000);
</script>

You can put it in a loop like follows
while(1)
{
echo 111;
sleep(1);
}

PHP is not well suited for what you want to do. Instead, use Javascript and the function setInterval(functionName, 1000), where functionName is a Javascript function that writes the message that you want.

Another way would be to refresh the page automatically:
<meta http-equiv="refresh" content="1">
<?php echo '111';?>

Related

Multiple php return values with jquery $.post

I dont really know how to ask this which is why I am asking it here. So if I was using some code like this:
$.post("/data/something.php", {stuff: 'hi'}, function(data){
$('#box').html(data);
});
Normally if you have php like this you only get 1 result:
<?php echo $_REQUEST['stuff'] ?>
I was wondering if there is any way for the php to send a bit of data, then a little bit more later without it just sending all of it at once like so:
<?php
echo 'Foo';
//Do stuff that takes time
echo 'Bah';
?>
There are 2 ways to accomplish this.
The first uses a standard workflow with the flush command (http://php.net/manual/en/function.flush.php). This means that you can do:
echo "Starting...\n"
flush();
// do long task
echo "Done!\n"
HOWEVER: This often won't work. For example, if your server uses deflate, the Starting likely won't get sent until the request is finished. Many other factors can cause this too (proxies, browser behaviour).
The better option is to use a polling mechanism. Your main script would write its progress to a file (with some session ID related filename), then delete that file when done. You would then add a second script to report the progress in this file (or completion if the file has been deleted) and your JavaScript would send an AJAX request to this checker script (maybe every second or two).
In PHP
<?php
echo 'Foo';
echo '||||';
echo 'Bah';
?>
In Javascript
var responses = data.split('||||');
//you will get
//Foo in responses[0]
//Bar in responses[1]
I expect that php has no problem doing that (as detailed by #Dave). The complicated part, is for javascript to retrieve the first part of the data, before the transmission completes...
I think what you are asking is answered here: Is it possible for an AJAX request to be read before the response is complete?
The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.
and...
So finally, yes it is possible, no it is not easy.

Echoing mysql statement inside of javascript

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.

how to run 'free -m' every minute & add to current page (php only)

I need to
run 'free -m' every minute
and then add the result to the previous results
So the script is going to run only of I call the free.php from my browser. I want to use php 5.3 + javascript/AJAX + html only (=no cron, jQuery etc)
set_time_limit(0);
$results = array();
while (TRUE) {
system('free -m', $result);
$results[] = $result;
sleep(60);
}
This kind thing would work great as a cron, however.
I know you don't want to use jQuery here, but it's just one tool available. You can totally replace it with whatever ajax library you prefer.
The critical thing is going to be managing a Javascript timer using setInterval.
// Here's the function that will be run.
function get_free_mem() {
$.get('/free_mem.php', {}, function(data){
// data contains the HTML output from the script.
// '#somewhere' is the HTML element that you want the
// output of the script appended to.
$('#somewhere').append(data);
}, 'html');
}
// And here's how we'll run it.
var timer = setInterval(get_free_mem, 60 * 1000); // 60 seconds
And here's free_mem.php:
<pre><?php passthru('free -m'); ?></pre>
Every 60 seconds, the get_free_mem function will fire, which will request the PHP script and append the output to an HTML element on the page.
(This code is untested.)
(Yes, I realize that the setInterval thing can backfire and cause uneven update timing if the called script takes a while to return, and that using setTimeout instead and re-triggering it on ajax completion is better practice, but I believe that the called script is simple enough that this shouldn't be too much of a problem here.)

Display process log on a web page

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.

Breaking a PHP code with Javascript confirm dialog?

I have PHP scrip that goes like this:
if ($cost_frm < $cost){
echo "<script type='text/javascript'>
var r = confirm('Input cost is lower than original. Sure?'));
If (r==true){
} else{
*** BREAK PHP SCRIPT ***
}
</script>";
}
And I'd like to stop ejecuting the script (or doing anything else) if the user clicks Cancel. Any tip?
You can't! PHP is server side, javascript is client side
Why not just put that entire validation into javascript?
Well I suppose if instead of running the whole script you broke it up into segments that you could activate using ajax, that might get you what you need.
You can't do that because the PHP is going to finish processing before the JavaScript runs.
PHP runs completely on the server, and only when it is done does it send the output to the browser, which then processes it. So by the time that box pops up, everything will be done.

Categories