I want to create a counter. I have a foreach loop value. I want show the count while the script is running. How can set a counter while the script is running?
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
echo "<p class='test'>Total Matched : </p>";
echo "<br>";
echo "Not Found : " .$k;
This question is (or at least should be) entirely unrelated to PHP. Use PHP to output your data, including the total count. Then, use javascript/jQuery to create a visual effect of counting from 0 to the total number, for example on document ready.
<p class='test'>Total Matched : <span>888</span></p>
Javascript
$(function(){
var item = $('.test > span');
var total = parseInt(num.text());
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
`
This won't work. The output is only shown after the PHP has finished executing.
PHP stands for: "PHP: Hypertext Preprocessor", notice the "Preprocessor" part, it preprocesses the page and creates the HTML, it cannot modify the HTML once it's ran.
You Can't show php's foreach's count while the script is running.
PHP doesn't work that way. PHP is a preprocessor for HTML. It converts the dynamic code into plain html at server side as a whole, and then it sends the whole HTML file to browser.
Thus, you don't have option to show php loop's counter value to the user side.
You Can alternatively use Ajax. But again, PHP will send whole ajax response at once only after php script finishes execution. You have to implement some javascript loop mechanism at client side to show the counter value one by one as suncat100 suggested.
If you want to show value updating animation to user you can try this,
PHP
$i=0;
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
HTML (JS)
<script>
$(function(){
var item = $('.test > span');
var total = <?php echo $i?>;
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
</script>
</body>
Use the both php and JS code in same page. put the JS code part just before ending </body>.
Related
I m trying to print out loop iteration one by one instead of one using ajax is this possible?
Like
iteration 1
iteration 2
etc but they should not at once but one by one as the loop work
Here is my ajax and php code.At this moment the whole code process and finally gives output instead of one by one
<div id="div1"></div>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$("button").click(function(){
$.ajax({url:"counter.php",success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<button name="button" value="button" style="width:200px; height:200px;">
Here is PHP code
<?php
for ($i = 0; $i < 10; $i++)
{
echo "<div>" . time() . ": Iteration $i</div>";
sleep(1);
flush();
}
?>
It's due to once you post a request loop get the response and revert the response to ajax method
loop execute so fast , you need to sleep the loop once it execute so time, so that once you got a result after some second again loop execute and you got again a response
please follow this timeout function to sleep loop for a while
Where i belong the param you pass throughout the loop and not lost the dynamic value....
> (function(i){
> setTimeout(function(){
>
> }, 1000 * i);
> }(i));
That's true. PHP will (by default) send the output if the full PHP script is executed. If you want a counter you should loop through the AJAX calls instead of your PHP code. This example will work:
var currentCounter = 0;
var countTill = 10;
function invokeCounter()
{
$.ajax({url:"counter.php?counter="+currentCounter,success:function(result)
{
$("#div1").html(result);
if(currentCounter >= countTill)
{
clearInterval(myCounter);
}
currentCounter++;
}});
}
var myCounter = setInterval(function()
{
invokeCounter();
}, 1000);
In your PHP you can get the current counter
<?php
echo "<div>" . time() . ": Iteration ".$_GET['counter']."</div>";
?>
I think you know this isn't a right solution for a webcounter, but you are probably experimenting/testing something in JQuery/AJAX/PHP.
Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.
I'm just learning PHP and Javascript in a JC class. I have the following for a school project. The following setInterval() runs every 3 seconds, however the embedded PHP code only runs the first time.
i.e. newVal gets updated the first time but doesn't change it's value on the following iterations. The script never telnets back into the server to find if the value changed.
setInterval(function () {
var newVal, mem;
<?php $telnet = new PHPTelnet();?>;
<?php $result = $telnet->Connect('ip_address','username','password');?>;
<?php $telnet->DoCommand('show process memory summary"', $result);?>;
<?php $result = preg_replace('/[\r\n ]+/',' ', trim($result)); ?>;
newVal = "<?php echo substr($result,61,7) ?>";
newVal = newVal / 10000;
mem.update(newVal);
}, 3000);
Thanks to some of the answers/comments below, this is what I did to make it work:
Javascript
setInterval(function () {
$.get("memAccess.php", function(return_value) {
mem.update(parseFloat(return_value));
});
}, 3000);
Separate PHP file
<?php
$telnet = new PHPTelnet();
$result = $telnet->Connect('ip_address','username','password');
$telnet->DoCommand('show process memory summary', $result);
$result = preg_replace('/[\r\n ]+/',' ', trim($result));
$result = substr($result,61,7);
echo $result;
$telnet->Disconnect();
exit();
?>
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
more on Ajax: Ajax Basics
I'm trying to increment the value of the java script variable and php variable simultaneously , so in my java script i do :
<script>
<?php $i=1;?>
for(var i=1;i<=5;i++){
var abc = $('<input>').attr('name','demo'+i).attr('value','<?php echo set_value('demo'.$i++));
<?php echo $i; ?>
}
</script>
However ,every time the value of $i echo`ed is 2 , logically it should increment number of times the java script loop iterates and echo 5 but its not , what am i doing wrong ?
The PHP code doesn't run at the same time as the Javascript code.
The PHP code runs on the server, before the client receives the page. The Javascript code runs on the client, after the client has received the page.
You'll need to write a loop in your PHP code that provides the full data to your Javascript code.
One common way of doing it would to put it into an array and encode it as JSON serverside, then feed the JSON to your Javascript for further processing. Note, no extra parsing of the data is needed on the Javascript side, if you just assign it to a variable - JSON is valid Javascript.
Further reading
JSON in PHP
JSON in Javascript
There is no loop inside this code! (If you ask the PHP interpreter).
It is simply a PHP script which outputs a few lines of text (that happen to be Javascript code, which happens to contain a Javascript loop).
You can try understanding this code:
<script>
<?php
echo "var data = [";
for ($i = 1; $i <= 5; $i++) {
echo "'".set_value('demo'.$i)."'";
}
echo "];";
?>
for (var i = 1; i <= 5; i++) {
var abc = $('<input>').attr('name', 'demo' + i).attr('value', data[i]);
}
</script>
What actually happens is, once you run this php file, the php block generate output something like:
var data = ['demo1 value', 'demo2 value', 'demo3 value','demo4 value','demo5 value',];
this is an array in javascript, that you can use in the javascript code below the php block.
I'm using PHP to echo out 50 video id's from an XML file. I use the video id's to embed 50 YouTube videos into my website. This works fine but I need to isolate the videos two at a time. I don't want the user to see all fifty videos at once. I want them to see two, then click next, see another two, then maybe click back, etc. etc.
Here's what I have so far:
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
while ($i < 49) {
$title = (string) $xml->query->results->item[$i]->title;
$videoid = (string) $xml->query->results->item[$i]->id;
$explanation = (string) $xml->query->results->item[$i]->explanation;
$i = $i + 1;
echo $title."<br />";
echo '<iframe width="400" height="225" src="http://www.youtube.com/embed/'.$videoid.'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>';
echo $explanation."<br /><br />";
}
So I think the best thing to do is echo all fifty items to the page inside divs labeled 0 to 49...then use JavaScript to hide all divs except 0 and 1 until you click a next button and it switches to hiding everything except 2 and 3...and so on...
But I'm not sure how to do that in JavaScript/jQuery. I think using .show() and .hide() would work but I'm not sure of the syntax.
You can use the following HTML structure:
Previous videos
<div class="video-row active">
<!-- First couple videos -->
</div>
<!-- Loop through all videos, writing the other rows -->
<div class="video-row">
<!-- Last couple videos -->
</div>
Next videos
Note: Use the active class only in the first video row to show them by default on the page load.
With CSS, hide all .video-row (using: display:none;) and show only .video-row.active (using: display:block;).
Finally, use the following Javascript (jQuery needed) to navigate between video rows:
jQuery('.prev-video-row').click(function (event)
{
event.preventDefault();
var prev = jQuery('.video-row.active').prev();
if (prev.length)
{
jQuery('.video-row').removeClass('active');
prev.addClass('active');
}
});
jQuery('.next-video-row').click(function (event)
{
event.preventDefault();
var next = jQuery('.video-row.active').next();
if (next.length)
{
jQuery('.video-row').removeClass('active');
next.addClass('active');
}
});
Honestly speaking, I don't think it's great to have 50 videos embedding in a page - regardless of visibility or not; simply because they will be processed by the browser despite not being visible. (Feel free to correct me if I'm wrong, but the browser is going to see, and process, the whole DOM - and just apply the styles to the "hidden" bits.)
Gustavo Straube has given a really good answer on how to do this if you want to have 50 elements in the DOM despite the effects it may have on both browser and bandwith.
I'd probably go for something more along the lines of parsing the XML, storing all the data as JSON then dynamically updating the DOM with jQuery from HTML supplied with a templating framework like Mustache.js.
/* Generate JSON */
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
$json = array();
while ($i < 49) {
$arr['title'] = (string) $xml->query->results->item[$i]->title;
$arr['videoid'] = (string) $xml->query->results->item[$i]->id;
$arr['explanation'] = (string) $xml->query->results->item[$i]->explanation;
$json[] = $arr;
}
echo json_encode($json);
Then, in your markup have something like the below, just to initialise your first x videos - in this example 10..
$(document).ready(function(){
var template = '{{$title}}<br /><iframe width="400" height="225"'
+ 'src="http://www.youtube.com/embed/{{$videoid}}?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>'
+ '{{explanation}}<br /><br />';
var html = '';
var i=0;
for(; i<10; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
Next up have an anchor (in this example #next) to get the next 10 videos..
$('#next').click(function(){
/* template, i and json are still in scope! */
var j = i+10;
for(; i<j; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
});
The advantage of this is it's also easy to do a previous anchor...
$('#prev').click(function(){
/* template, i and json are still in scope! */
var j = i -10;
i -= 20; //10 for the current page, 10 for the start of the previous page
for(; i<j; i++){ //rebuild div content of previous page
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html);
});
Just to re-iterate, this is an alternative solution - I've suggested it as using JSON is a little bit more lightweight and more flexible than XML, and it also removes the requirement for having 50 DOM elements that aren't in use at one time. There may be a reason you've chosen the implementation that you have, but it's not the implementation I would take if I was given this problem!
For html like:
<div id="section0"></div>
Your jquery would look like:
$(document).ready(function() {
$('#section0').show();
$('#section1').show();
$('#nextButton').click(function(e){
e.preventDefault();
$('#section0').hide();
$('#section1').hide();
$('#section2').show();
$('#section3').show();
return false;
}
});
And so on...