i have multiple timers on a page but the code doesn't seem to work for it.
in the code below the timer for each post gets started with onload function which calls the jquery code
the code i used i got it from another thread here i just modified it to work with onload for each span but it doesn't work then
<?php
$i=0;
$timeleft="05:00:30";
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>" onload="start_timer(<?php echo $i; ?>,<?php echo $timeleft; ?>)"> <?php echo $timeleft; ?> </span>
<?php $i++;endwhile;wp_reset_postdata(); ?>
<script type="text/javascript">
function start_timer(num,time){
$(document).ready(function() {
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown'+num);
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
}
</script>
onload is only supported on the following elements
you can do something like this:
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>start_timer(<?php echo $i; ?>,'<?php echo $timeleft; ?>');</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>
Edit:
change you javascript to this:
<script type="text/javascript">
function myFormat(num){
return (num < 10)? ("0"+num): num;
}
function StartTimer(num, time){
this.parts = time.split(':');
this.hours = this.parts[0];
this.minutes = this.parts[1];
this.seconds = this.parts[2];
this.span = $('#countdown' + num);
}
StartTimer.prototype.myTimer = function(){
var s = this.seconds;
var m = this.minutes;
var h = this.hours;
var sp = this.span;
var t = setInterval(function(){
s--;
if(s == -1) {
s = 59;
m--;
if(m == -1) {
m = 59;
h--;
if(h == -1) {
alert("timer finished");
clearInterval(t);
return;
}
}
}
//console.log();
//console.log();
//console.log();
sp.text(h + ":" + myFormat(m) + ":" + myFormat(s));
}, 1000);
};
</script>
and your while loop:
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>new StartTimer(<?php echo $i; ?>,'<?php echo $timeleft; ?>').myTimer();</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>
you can also check it in JSFiddle here
Related
I created a numeric pagination that loads the data via AJAX.
This is the code:
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${'page=' + page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
});
The code works, but when I refresh the page the data are loaded again from the first page. test_ajax
Ex: If I click the button that loads the page 2 when I refresh the page the data are displayed from the page 1.
There is a way to remain on the same page even after the page refresh?
pagination2.php
<?php
$rowperpage = 10;
$page = 1;
if($_REQUEST['page'] > 1)
{
$p = (($_REQUEST['page'] - 1) * $rowperpage);
$page = $_REQUEST['page'];
}
else
{
$p = 0;
}
?>
<?php
$visible = $visible ?? true;
$products_count = count_all_products(['visible' => $visible]);
$sql = "SELECT * FROM products ";
$sql .= "WHERE visible = true ";
$sql .= "ORDER BY position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage."";
$product_set = find_by_sql($sql);
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>No products</h1>";
}
while($run_product_set = mysqli_fetch_assoc($product_set)) { ?>
<div style="float: left; margin-left: 20px; margin-top: 10px; class="small">
<a href="<?php echo url_for('/show.php?id=' . h(u($run_product_set['id']))); ?>">
<img src="staff/images/<?php echo h($run_product_set['filename']); ?> " width="150">
</a>
<p><?php echo h($run_product_set['prod_name']); ?></p>
</div>
<?php }
mysqli_free_result($product_set);
?>
<section id="pagination">
<?php
$url = url_for('index_all.php');
if($_REQUEST['page'] > 1)
{
$page_nb = $_REQUEST['page'];
}
else
{
$page_nb = 1;
}
$check = $p + $rowperpage;
$prev_page = $page_nb - 1;
$limit = $products_count / $rowperpage;
//echo $limit;
//exit;
$limit = ceil($limit);
$current_page = $page_nb;
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}
When the document is ready you use load_data(1);
That's wrong because if someone refreshes at page 5 it starts anyway from page 1.
Check the current page everytime you refresh.
The code should be something like this:
var url_string = window.location.href;
var url_parts = url_string.split('/');
var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n)
var page;
if(piece.substring(0, 5) === 'page=') {
page = parseInt(piece.substr(5));
} else { //if it's the first time you landed in the page you haven't page=n
page = 1;
}
load_data(page);
This is the first time that I have make (I mean, I try) pagination without page refresh by using Ajax with Jquery, PHP and Mysql.
Problem: Pagination links are not working.
Site content is working.
This is a link to the test page: testpage1
Thank you in advance for your help.
1. Ajax(index.php)
<div id="page">
</div>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#page').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
2. PHP (pagination2.php)
if($page_nb > 1) {
echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
//echo '<span style="cursor:pointer;" onclick="LoadData('.$prev_page.')">Back</span>';
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
//echo "{$i}";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
//echo '<span style="cursor:pointer;" onclick="LoadData('.$next_page.')">Next</span>';
}
3. I think I found a solution
A. Ajax
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"GET",
data:{page:page},
success:function(data){
$('#page').html(data);
//alert('Successfully called');
},
//error:function(exception){alert('Exeption:'+exception);}
})
}
//load_data(1);
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
B. Links
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
//echo "{$i}";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
//echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}
i used php implode method to an array inside javascript.Yesterday it was working fine but now am getting SyntaxError: syntax error <br/> in firebug.
I closed the php tag correctly but not sure why is this coming.
function create() {
var sTop = Math.floor(Math.random() * (windowHeight));
<?php
for ($i = 1; $ i <= 28; $i++) {
if(${'h'.$i} != NULL) {
$sel[] = ${'h'.$i};
}
}
$format= implode('","', $sel); ?>
var selectedImg = new Array("<?php echo $format; ?>");
}
I am getting above the
var selectedImg = new Array("<?php echo $format; ?>");
when I viewed the JavaScript in FireBug.Can anyone help?
A fix ..
function create() {
var sTop = Math.floor(Math.random() * (windowHeight));
<?php
$sel = array();
for ($i = 1; $ i <= 28; $i++) {
if(${'h'.$i} != NULL) {
$sel[] = ${'h'.$i};
}
}
$format = !empty($sel) ? implode('","', $sel) : ""; ?>
var selectedImg = new Array("<?php echo $format; ?>");
}
Other method with json encode
function create() {
var sTop = Math.floor(Math.random() * (windowHeight));
<?php
$sel = array();
for ($i = 1; $ i <= 28; $i++) {
if(${'h'.$i} != NULL) {
$sel[] = ${'h'.$i};
}
}
?>
var selectedImg = <?php echo json_encode($sel); ?>;
}
A while ago, I created (with much help) a program that uses php and javascript to make some ambient music by randomizing an array of .ogg files. Now I am trying to re-write it with js alone.
The new code immediately below does not work (the .ogg files do play properly when clicked individually, but nothing happens when you press the 'start' button, which is the main feature). (The code below that (containing php) does work.) I've been over the new code several times and I think I've got the 'typos'. I'm pretty sure the problem is in the syntax of the window.setTimeout line, but haven't quite figured out how it should be.
Thanks for any help you can offer!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
</script>
<script type="text/javascript">
var tonesTotal = 150;
function getDelays(tonesTotal)
{
var return_array = array();
for (var i = 0; i < tonesTotal; i++)
{
var r = getRandInt(0, 600);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays(tonesTotal);
$(document).ready(function()
{
$("#start").click(function()
{
var base = 'sound';
for(var i = 0; i < tonesTotal; i++)
var id = base + ((i + 1) );
window.setTimeout ("document.getElementById('" + id + "').play()", delays[i]);
});
});
</script>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<script>
var tonesTotal = 150;
var samples = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for (var i=1; i <= tonesTotal; i++)
{
shuffle (samples);
var samplepick = samples[0];
document.write ("<audio controls id='sound" + i + "'><source src='" + samplepick + "' type='audio/ogg'></audio>");
}
</script>
</body>
</html>
PREVIOUS CODE:
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
//$randC = rand(1,4);
$C = 150;
function getDelays($C)
{
$return_array = array();
for($i = 0; $i < $C; $i++)
{
$r = rand(0, 600);
$delay = $r * 1000;
array_push($return_array, $delay);
}
return $return_array;
}
echo "<script type=\"text/javascript\">\n";
echo "var delays = new Array();";
$delays = getDelays($C);
for($i = 0; $i < sizeof($delays); $i++)
{
echo "delays[" . $i . "] = " . $delays[$i] . ";\n";
}
echo "
$(document).ready(function()
{
$(\"#start\").click(function()
{
var base = 'sound';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", delays[i]);
}
});
});
</script>
";
?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<?php
$samples = array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for ($i=1; $i<= $C; $i++) {
shuffle ($samples);
$samplepick = $samples[0];
echo '<audio controls id="sound'.$i.'">
<source src='.$samplepick.' type="audio/ogg">
</audio>';
}
?>
</body>
</html>
When I tested it locally I found a Javascript error in the getDelays() function: First line of code should be:
var return_array = new Array();
I'm having this jQuery script thats adding a timer when someone voted he needs to wait 3 minutes
the script is working till the moment I'm getting the remaining time with php
$(document).ready(function(){
alert("1");
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
var ss = countdown % 60;
if (ss < 10)
ss = "0" + ss;
seconds.innerHTML += ":" + ss;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
/*$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');*/
}
}, 1000);}
$(".upvote").click(function(){
alert("2");
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(180), par);
});
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
so in this part I'm getting the time to wait for the next vote with php and this does not seem to work what's going wrong ?
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
You should just use a setTimeout(function(){},(3 * 60 * 1000)) to block the vote functionality.
//Block the vote here
setTimeout(function(){/*unblock here*/},(3 * 60 * 1000))
Replace this:
Timer(Math.round(<?php echo $wait; ?>, par); } });
With:
Timer(Math.round(<?php echo $wait; ?>, par)); } });
;)