I have a function called $function. I want my code to add 1 to $function every second, and in "live".
$function = 100;
$add = $function + 1;
echo $add;
How do I run/execute $add every second? I would like to see the number getting bigger in "live" (without having to refresh the page every time I want to see the result).
PHP is a server-side language which can only actually do anything on your server. If you want things to update dynamically on the client (i.e. your browser) you need a client-side language, like JavaScript. Generally server-side languages like PHP generate client-side code which is then transferred over a network to your browser.
For example, you could get your PHP server to output the following HTML:
<html>
<body>
<div id="number">1</div>
<script>
var text = document.getElementById("number");
var number = 1;
window.setInterval(function() {
// code in here will repeat every 1000ms
number = number + 1;
text.innerText = number;
}, 1000);
</script>
</body>
</html>
If you're just learning to program, you might enjoy learning HTML and JavaScript more, without worrying about the server for now, as you can get to see the results of your program more dynamically. A good resource might be Codecademy or direct from Mozilla
Related
I have come across this problem before and expect to do so again: I want to run a subtotal calculation in both javascript and PHP. I may want to change the calculation at some point.
It needs to run in javascript to maximise the speed of the calculation, so that the user knows what to expect.
It needs to run in PHP so that I am getting a valid subtotal which a malicious user cannot interfere with.
As such:
If I only run the calculation on the client-side (in javascript), a malicious user may hack the javascript and change the subtotal.
If I only run the calculation on the server-side (in PHP), an AJAX call would have to be waited on for the user to get their updated subtotal.
So I want to perform the calculation on both sides. The only way I have seen this done is by programming the calculation in PHP and programming the calculation in separate javascript.
My question is, what pattern, technique or technology would people recommend that I use to create the calculation on the server-side and make it compatible with javascript when it is sent to the client-side?
An idea I had, for example, was a PHP array for the calculation, which gets translated into PHP code and javascript code, e.g:
array(
array(type => "operand", "name" => "variable_A"),
array(type => "operator", "name" => "multiply"),
array(type => "operand", "name" => "variable_B"),
)
This might convert into PHP:
return $variable_A * $variable_B;
And into Javascript:
return variable_A * variable_B;
That's an example operational pattern. I don't know what real ones would look like if they exist.
ajax?
you can pass all the variable entered with javascript and leave the process server based.
or i misunderstand your question?
The way I think about your problem is like you described it: do double calculation.
And I believe that's how the "big boys" do it.
Example: Add up two numbers.
So you have a code like this:
HTML snippet:
<form method="post" action="/add.php">
<input id="firstOperand" name="firstOperand" placeholder="First operand"/>
<input id="secondOperand" name="firstOperand" placeholder="Second operand"/>
<input type="submit" onclick="doCalculation()" value="Add"/>
</form>
<div id="result" />
Your JS might look like:
function doCalculation() {
var first = parseInt(document.getElementById('firstOperand').value);
var second = parseInt(document.getElementById('secondOperand').value);
var result = first + second;
// the minimum amount of error checking
if isNan('result') return false;
document.getElementById('result').innerHTML = result;
// Now use some framework (like jQuery) to make an Ajax call and pass the result to callback.
Framework.Ajax('/add.php?format=json', 'POST', {first: first, second: second}, callback);
return false;
}
function callback(response) b
var res = response.json.result;
var resultEl = document.getElementById('result');
var errorEl = document.getElementById('error');
// if our result is not correct, we want to update the user on it
if (res != parseInt(resultEl.innerHTML)) {
Framework.removeClass(errorEl, 'hidden');
}
document.getElementById('result').innerHTML = res;
}
Of course, your PHP result page (add.php) would return json with the result. The added value here is that you can also return a plain HTML result (like if js is disabled).
Your callback could also check if there was an error in the returned result and display that error message too. Or if the result times out, display a notification that the "result" is not saved. But that's out of the scope of the question, I guess (at least, out of the scope of the answer).
Note: this is just the code off the top of my head, not tested, written directly in the answer box, probably a few things should be done better.
I'm trying to display the results while PHP script is running, as example.. a really long loop, i want it to echo the results while the page is loading, I searched really a lot through this and i couldn't find the good answer, After googling i found people saying use ob_flush from this question .. but it didn't work, as well as enabling the implicit_flush from php.ini , still didn't work
it only loads when the process is finished, i tried to run a for loop like this
ob_start();
for($i=0; $i<500; $i++){
echo "hm\n";
ob_flush();
}
ob_end_flush();
and still, didn't work.. it shows them all at once
My last guess now is that it needs more PHP configurations to enable/disable some stuff,
or.. it could also be apache2 configurations ?
What are the config settings that are related to this ? settings that needs to be disabled/enabled through Apache or PHP configurations ..
P.S. : I'm sure its possible to be done using PHP alone, I saw it done on GoDaddy hosting and saw it on several websites, of them http://www.checker.freeproxy.ru/checker/index.php .. if you try to submit it will show the results normally without using ajax, the website uses PHP and Apache, there's a mystery secret behind this
I used this way from this answer
while(1) {
echo "should display these lines on browser while in infinite loop.<br>";
flush();
}
or using the for loop, they both work fine, and it to make it more accurate i use ob_flush() with flush()
for($i=0; $i<5000; $i++) {
echo "should display these lines on browser while in infinite loop.<br>";
usleep(30000);
ob_flush();
flush();
}
they both work fine without ajax
Check my post here: Show progress bar in php while loop
It has some sample code as well, and covers pretty much everything you need.
PS: It can't be done with PHP alone, you need to do this with AJAX + PHP (client + server side coding). This is because the response is sent to the browser only after the file is fully interpreted.
You can't do this with PHP. PHP is run server side so it executes before the HTTP response is sent back to the browser.
You would need to use AJAX to achieve this.
You may also look at websockets to achieve this kind of thing.
You could also cheat and load all the data into a hidden list, and then use javascript to show the list items one by one after the page has loaded. :)
As mentioned above, Ajax would be the best method.
You'll need 3 files, a html file or php file that heads the job, a javascript file with your ajax in it and the php file running your script, here's an example of how you could do this. The rest is up to you if you need it tweaking for whatever you are trying to do, but it should give a sequential redout if you break up your php accordingly.
go.hml:
<html>
<head>
<title>Insert Title Here</title>
<script src="ajax_example.js" language="javascript"></script>
</head>
<body>
<form action="javascript:insert()" method="post">
<input type="text" name="limit" value="" id="limit"/>
<input type="submit" name="Submit" value="Go"/>
</form>
<div id="text_response"></div>
</body>
</html>
ajax_example.js:
// make script work for internet explorer too
function createObject(){
var request_type;
var browser = navigator.appName;
if(browser == 'Microsoft Internet Explorer'){
request_type = new ActiveXObject('Microsoft.XMLHTTP');
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var response = '';
var current = 0;
var limit = 0;
function insert(){
current = 0;
// write to the document
response = 'Hang on...';
document.getElementById('text_response').innerHTML = response;
// set the limit and run the loop script
limit = encodeURI(document.getElementById('limit').value);
limit++;
loop_file(current);
}
function loop_file(i) {
// open the php file you wish to run, the 'hm' and 'rand' are optional, obviously
http.open('get', 'file.php?hm='+i+'&rand='+Math.random());
// run the insertReply function
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply(){
if(http.readyState == 4){
response = response+'<br />'+http.responseText;
document.getElementById('text_response').innerHTML = response;
current++;
// this runs like a pseudo for loop and will loop until it reaches the 'limit'
if(current < limit){
loop_file(current);
}else if(current == limit){
//create end script here
}
}
}
file.php
<?php
echo isset($_GET['hm']) ? $_GET['hm'] . " - hm\n" : "hm\n";
?>
for($x=0;$x<100000;$x++) {
echo "hello $x";
}
So, normally, it will finish processing everything first and then print everything at once. Is there a way to just keep printing the message as the command is sent, so that I'll see a new hello $x appended one by one or do I have to use jQuery/JavaScript?
Update:
I ask because I'm trying to run a long test script and have it show all the results 1 by 1 on the browser so I don't have to go check the logs and could just visually see the color coded results. I'm trying to make a similar effect to this: http://tools.css3.info/selectors-test/test.html If anyone could provide a short sample of the jQuery (if it has to be done this way), I would appreciate it.
Although it's possible by controlling the output buffer, I wouldn't do that, mainly because it will delay the JavaScript DOMReady event.
If you're looking for a visual effect, you should use JavaScript (but I don't see any reason for Ajax based on what your question says). It can be accomplished with a simple setInterval. Considering an initially empty <div id="hello">:
var i = 0;
var timer = setInterval(function(){
if(i == 10000) {
clearInterval(timer);
return;
}
var div = document.getElementById('hello');
div.innerHTML += 'hello ' + i + '<br>';
i++;
}, 250);
I just saw your edit, and now I think you actually should use Ajax! The example you linked to does. Basically, you have to setup a test queue in JavaScript, where each test has an unique URL. Then it's just a matter of firing one request at a time with Ajax (jQuery and $.get would be the easiest way to go). The following assumes an <ul> instead of the div from my previous example, and that the server will respond with a success or failure message for each test:
var tests = [
'http://example.com/test1',
'http://example.com/test2',
'http://example.com/test3',
];
function processQueue() {
if(tests.length > 0) {
var test = tests.shift();
$.get(test, function(response) {
$('#some_ul').append('<li>' + response + '</li>');
processQueue();
});
}
}
processQueue();
Yes, if you disable output buffering: http://php.net/manual/en/book.outcontrol.php
But as #Blender suggests you'd probably be better off doing this with AJAX (commonly done using jQuery).
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';?>
I have the following jquery code:
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
But I need $day_1 in the php echo statement to reflect the variable "count", so in theory it should be something like "echo $day_count". Is it possible to pass the var to php?
php & jquery coding:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
?>
<script type="text/javascript">
var chart1;
var count=1;
var formfig=17;
var formfig2=2;
function chartdraw(){
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
The short answer here is no.
To understand what's possible, you need a deep understanding of what's going on. Your PHP code is building an HTML document (with embedded JavaScript) and sending it on to the web browser. Once the web browser (which is, of course, running on the user's machine, not your server) renders that page, it will execute the javascript. This is when the javascript variables begin to actually mean something. Until then, they are just text getting sent across the network. This point is long after the PHP code has finished running. Your server has already closed down that php instance as it sent the code to the user.
Keeping that in mind, you can send the value of a javascript variable (or any number of other things) back to your server with something called an ajax request. Essentially, this will send some information (the variable's value, and the name of the page you want) back to your server, which will in turn cause your server to build a new web page, which can have PHP code in it. That web page's content will get returned to another bit of javascript you can provide -- called a 'callback' -- which can take the page created by the second php script and make use of it. This is, of course, fairly resource intensive.
Unless you plan to do something that ONLY PHP can do, I would recommend finding a way to do as much of your logic as possible in javascript. This alleviates all these complex problems and keeps all the hard work on the user's machine.
If you can structure your code so your php code provides all the data the javascript code needs before the php finishes running, you can get away without doing anything fancy with ajax. Here's an example:
<script type="text/javascript">
var days = {};
<? for($day = 0; $day < 30; $day++) { ?>
days.<? echo $day ?> = "<? echo get_day_info($day) ?>";
<? } ?>
</script>
What this will do is create a javascript object called days. Then it will fill in days.i for i from 0 to 30. It assumes you have a function called get_day_info($day) which takes a day and returns the info for that day. I'm assuming here that you're dealing with strings -- if not, you will need to remove the quotes, and possibly do other things to wrap the data depending on what format it takes.
I belive the only way is using ajax. http://api.jquery.com/jQuery.ajax/
Not without changing your approach significantly.
The problem is that PHP exists entirely on your server, where javascript exists in the browser. PHP does really know anything about javascript. PHP will completely render your page before any javascript has been run at all. So there is no way to get this value back in easily.
You can use ajax in order to run javascript which can load data or hit URLs on your server, but you cant simply substitute javascript variables in PHP. The reason you can do it with PHP variables is because the PHP actually is generating the javascript.
Have javascript store the value in a hidden field and pick up the value with PHP that way?