PHP timer output into HTML div every second - php

I developed a PHP countdown timer (3hrs specifically in hrs, mins and secs) - countdown.php. The output is within a <div> tag in another page - index.html.
I want an AJAX or Javascript that would make the output dynamic (that is changing figures like normal timer). I do know that AJAX can make the page refresh every second in the background (asynchronously), but I've not been able to achieve that.
Presently, the output only changes when I refresh the HTML page. I also want a PHP script to be triggered when countdown gets to zero.
countdown.php
<?php
//some codes left out
$remainingHour=floor($secsdiff/3600);
$remainingMinute=floor(($secsdiff-($remainingHour*60*60))/60);
$remainingSecond=floor(($secsdiff-($remainingHour*60*60))-($remainingMinute*60));
?>
index.html
<div id="timer">
<?php echo "$remainingHour hours, $remainingMinute minutes,
$remainingSecond seconds";?>
</div>

Make sure your using JQuery in your HTML page (Follow the tutes on the JQ website if this is new to you, It's really very easy)
Then once your up and running with that, use JQuerys Get function to update your div:
http://api.jquery.com/jQuery.get/
You should be able to get it up and working in 30 mins or less, it's very simple.

If this is just a small item on a larger page, I would use Ajax or JavaScript. With Ajax you should be able to check for 0 values and if it is reached, notify that to the server, where server will perform specification action.
You probably can do that with JavaScript a s well which might be more desirable for such small tasks.

You should use setTimeout function in javascript, see https://stackoverflow.com/search?q=[javascript]+setTimeout&submit=search
When the timer will be over, simply call a new URL to execute the next php script (still in javascript), like :
document.location.href = http://foobar.tld/new_page

Related

why $(element) not works directly. but works in function

When i try to select any element which is the result of ajax call it don't get selected using $(element)
but when i try to select that element in any function it will selected
Example: if i select an element with id change.
hello.php is
<?php
echo '<span id="change"> hello </span>';
?>
html in main.php is
<div id="content">
</div>
and script in main.php
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$("#change").css({"backgroundColor":"red"});
</script>
this script don't change the color of span , I know it will not work because at the time when 2nd statement is executed their was no element with id change,
and $("#element") can't find the element with id change
But when i try $("#change") in any function it will change the color of span.
for example if i use
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
setTimeout(function(){$("#change").css({"backgroundColor":"red"});},0);
</script>
Please note i set the delay time to 0 sec. But this works and change the color of span with id change. I mean now the $("#change") can find the element with id #change
and if i use $("#change") in ajax function then also it works.
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$.post("example.php",function(r,s){$("#change").css({"backgroundColor":"red"});});
</script>
Can someone explain why this happen , why in other two examples $("#change") selects the element. even their is no delay in executing the function
Is all about timing. When you get content from the server and you try to inject it in DOM, it will take a bit to render. When you use setTimeout with whatever value, you push the inner function in the event loop. The result is that it will be executed after minimum time that you specify - in your case 0, but only when the stack is empty. During this time, things are rendering in DOM and you get to have access to those elements. You should watch this video for a much better explanation of what is going on: https://www.youtube.com/watch?v=8aGhZQkoFbQ
This is due to the asynchronous nature of your post command. The rest of the script doesn't get halted till the post get finished. Rather than that, it get's executed even though the post command is already under progress. What you do with the timeout function is that you delay the execution of the jquery selection by a fraction of time, and this gives the time for the post to finish.

Using PHP in Javascript

I just found out that PHP can be used in Javascript like this:
<script>
function seeTime() {
alert("<?php echo time(); ?>");
}
</script>
<button onclick="seeTime();">Click Me</button>
The above code will popup an alert message with the Unix timestamp every time the button "Click Me" is clicked. But the problem is, the time remains the same everytime you click the button until the page is reloaded.
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
Yes, just don't use PHP at all:
function seeTime() {
alert(Math.floor(new Date().getTime()/1000));
}
You are getting confused between PHP and JavaScript. PHP is not being "used" in JavaScript. PHP runs on the server and generates the page, which is then sent to the browser.
<?php echo time(); ?> is replaced with the current timestamp, then sent to the browser which runs the JavaScript.
As far as I know it's impossible, PHP code is compiled server-side, so all you return from a php compilation are static value, you must use AJAX to refresh the time value.
You could set the time with JS if you wish.

Is it possible to call a Javascript function from HTML independent of an event?

I have a condition in php based on some session variables. If condition passes, I want to call a Javascript function which is updating my current webpage. Is it possible to place such a call to Javascript function independent of a button or a link or the window load function?
If I am understanding you correctly, just use php to output the javascript function. It will fire once, if you need.
<?php
if ($_SESSION['condition']=="foo") {
echo "<script>","/n";
echo "doThisNow();","\n";
echo "</script>","\n";
}
?>
Or, you could echo out the session variables as javascript variables in the same way, and then do the conditional check in javascript.
As proposed in another answer you can output a Javascript call whenever the page is loaded.
However, if your event cannot wait until the page is reloaded, then I suggest you setup some javascript to poll a page every X number of seconds (using AJAX) and do something when the values change.

How do I use jQuery to insert PHP tags through the DOM?

Here is what I'm trying to do...
$("div").prepend("<div id='comment-number'><?php the_comment_number(); ?></div>");
Is there some way to get this to work?
<div class="gallery-item">
<div class="comment-number"><!--?php echo htmlspecialchars(the_comment_number()); ?--></div>
</span>
<span class="gallery-icon">
<img src="http://mysite.com/test/wp-content/uploads/2011/06/fff-150x150.gif">
</span>
</div>
PHP is executed on the server, but JavaScript code (jQuery) is executed later, in the web browser. For that reason, PHP can produce JavaScript code, but JavaScript can't produce PHP code.
The <!--? in your posted output shows that something is filtering our your PHP code. So the problem isn't your PHP code, it's that you're not actually executing PHP code. If it's a .js file, PHP almost certainly can't be included.
If PHP were being evaluated (ex. if this were in a <script> tag in a .php file), this should produce valid JavaScript code that will do what you want:
$("div").prepend("<div id='comment-number'><?php echo htmlspecialchars(the_comment_number()); ?></div>");
1) php is SERVER side scripting
2) javascript is CLIENT side scripting (generally)
so this is what happens:
1) User opens up your page http://example/
2) Your CLIENT sends GET request to http://example/ server
3) Apache (given you run on it) captures the request, based on the server config approaches index.php (index.html, etc). If php is installed, your index.php will be parsed by mod_php module
<<<< this is where SERVER side scripting is activated
4) outcome of the parsing of index.php will be then transferred back to CLIENT
5) CLIENT will digest the outcome received by SERVER
6) If there are javascript calls, those are executed either immediately OR when document is loaded (based on approach)
That's it. Here normal request life ends.
NOW if you want your page to dynamically update some parts of it, here is how you do that:
1) Usually to update your page dynamically, you would use AJAX approach. When AJAX request is created, 2-7 happens again, but this time the caller is your ajax process and information which is received is sent back to that process to decided what to do with it.
Okay, some coding:
1) index.php
<!-- include jquery, etc //-->
<div id="comments"></div>
<script>
function fetch_comments(){
$.get("ajax.php", null, function(data)){
// this is called, when response from SERVER is received
$("#comments").prepend(data);
setTimeout("fetch_comments", 5000); // fetch again in 5 seconds
}
}
$(document).ready({
fetch_comments();
});
</script>
2) ajax.php
<?php
//fetch comments, return them for CLIENT
echo "<p>Comment on " . date("Y-m-d H:i:s") . "<br />Lorem Ipsum</p>";
This should help you understand the whole process. Did not test the code, but should be quite ok.
do a .ajax() query to PHP script that will provide you value of the_comment_number(); and put result to comment-number by $("#comment-number").prepend(result); on success event in ajax query.
Remebmer that PHP script have to have connection to database and pass to it all variables you need (like entity id, article id, page etc.). You can do it by GET or POST.
Request is sended by browser so session/cookies will be the same unless you changed it in current request.
PHP is executed on the server side so you cannot call it from javascript
You can try something like this which will render once the page loads
$("div").prepend("<div id='comment-number'>"+ <?php the_comment_number(); ?> +"</div>");
Couldn't you just add the value directly to the template instead of using javascriot? eg:
<div class="gallery-item">
<div class="comment-number"><?php echo (the_comment_number());?></div>
...
</div>
Also you have a </span> tag with out matching <span> tag in your example.
As already told, you can't produce or call php code from javascript directly(you need to make an ajax call or form submit). You need to make ajax call using jquery to fetch the comment number and then update it into div.
However, you may want to look at this library - http://www.phplivex.com/ .It may help you in doing things your way. It allows you to call user defined php functions in javascript using AJAX internally.
Reading through this disccussion and from what i understand you want to acheive.. You gotta figure how your page is served. If it is an .php file that is serving the content, then you wont need Javascript at all and could get your function call to work by adding the function between the div as so..
<div class="comment-number"><?php echo htmlspecialchars(the_comment_number()); ?></div>
Assuming you don't have access to the .php or if its a .html/htm page that serves the content then your only bet would be to use ajax. That is make an ajax call to a php file(on the same domain) that makes your function call and echos the comment no. The Ajax will retrieve the echo'd comment no. which you can append/prepend to the desired

strategy to split up php output into smaller outputs (ajax, php) (nested ajax calls, ajax within ajax?)

I don't know the correct terminology to search for the solution. Please suggest a strategy to break up the php output into small chunks and pass them stepwise to ajax's responseText.
The project is an ajax webpage that takes a text string (lastname) and passes it to a php program. The php code takes the last name and randomly fetches 3 people with different first names, and puts it into an array. Once that is done, the php code will contact outside servers to retrieve info associated with each name, and output the info to a div of the webpage. The process of getting data from the outside servers is very slow.
This code is basically done, but the whole process takes a very long time to generate the output on the screen. Is there a way (a strategy) to output each step of the php code immediately instead of having to wait for the complete code?
My pseudo php code is like this:
<?
get 3 names; //output this immediately
foreach name { get phone number }
?>
Alternatively, I could get a name and the phone#, and output it immediately before moving to the next name.
Are there php or ajax codes/functions/strategies that would achieve this? Please suggest solutions or search keywords.
Addition/Edit:
Thanks for the suggestions. Is it possible to execute another ajax call after the parent ajax call? I initially went that route, but my testing of nested js/ajax call did not work. It could be due to syntax errors, please look over the code.
The test code in the testajax.php (or testajax.html) file for the ajax call XHR.responseText is
<div id="name" >JAM <div id="numa" >
<br />
<br />text holder >>
<script type="text/javascript">
var pid=document.getElementById("numa").parentNode.id;
alert (pid);
document.getElementById('numa').innerHTML += 'append text>> ';
document.write(' docwrite');
</script>
</div>
</div>
<br />
<br />ending text
If I view the file testajax.php (or testajax.html) directly, I would see
JAM
text holder >> (an alert window) append text>> docwrite
ending text
but if I do an ajax call of the testajax.php file, all I would see is
JAM
text holder >>
ending text
The code inside the <script> </script> tags does not run after the ajax call
can someone explain this, and offer a fix?
TIA
Without knowing the actual code and code-based answer is hard. But, here's an idea.
When you get the three names, return them to the page and display them. Then, for each one, in a different AJAX call, call the phone info. I'm not positive if javascript will make all three calls independently of each other, but that would at least display all 3 names, and then each phone info one at a time.
Edit
Workflow:
Javascript sends a name to php via ajax.
PHP returns 3 names to js
js appends 3 divs to the page, one with each name.
js makes 3 requests to php, sending 1 name per request.
php returns phone info / whatever else to js
js takes info and adds it to the respective div
In theory, yeah, you can call flush() (and ob_flush() as necessary) to ensure output is sent from PHP.
However, the web server may add buffering of its own outside of the scope of PHP (most commonly, if mod_deflate is in use on Apache); and you'd have to be careful about delimiting your response chunks so they're not read by the browser until a chunk is complete.
In any case not all browsers can read the responseText from an XMLHttpRequest until the request is fully complete. So for it to work on all clients, you'd have to try a different mechanism, such as the old-school HTML-iframe-containing-multiple-<script>s.
Summary: it's a bunch of hassle, and perhaps not really worth it. A simpler-to-deploy possibility would be separate AJAX requests for each name.

Categories