0

I am working on a jquery/php countdown timer and the output is not as expected

Here is the below code

<p id='FeedExpire-".$id."' class='FeedExpire' style='display:inline-block;'>".$expires_by_cleaned_new."</p>

Picking up the innerhtml contents of a p tag and running it in a loop to display the count down timer for each element in jquery

var x = setInterval(function() { 
$('.FeedExpire').each(function () { 
   alert(document.querySelector('#'+this.id).innerHTML);    
   var deadline = new Date(document.querySelector('#'+this.id).innerHTML).getTime();
});

But not getting the result as expected .i get the expected results and it changes in instant(Screenshots attached below )

Complete code below

Expected result

Error

$( document ).ready(function() {            
   $.ajax({
       type: "POST",
       url: "http://192.168.1.11/Retrivedataforhomefeed.php",
       //data: {email:email,userId:userId,displayName:displayName,givenName:givenName,},
       cache: false,
       success: function(data) {
           var results=data;
           document.querySelector('.Homefeedstart').innerHTML = results;
           //alert(document.getElementsById('DBPostExpireBy-1').innerHTML);

           var x = setInterval(function() { 
               $('.FeedExpire').each(function () { 
                   alert(document.querySelector('#'+this.id).innerHTML);   
                   var deadline = new Date(document.querySelector('#'+this.id).innerHTML).getTime();
                   var now = new Date().getTime(); 
                   var t = deadline - now; 
                   var days = Math.floor(t / (1000 * 60 * 60 * 24)); 
                   var hours = Math.floor((t%(1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
                   var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)); 
                   var seconds = Math.floor((t % (1000 * 60)) / 1000); 
                   document.getElementById(this.id).innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; 
                   if (t < 0) { 
                       clearInterval(x); 
                       document.getElementById(this.id).innerHTML = "EXPIRED"; 
                   } 
               });
           }, 1000); 
           //});
           //var FeedDatareturned=$(".FeedExpire").attr('id');
           //alert(FeedDatareturned); 
       }
   });
});
<?php
    header('Access-Control-Allow-Headers: X-Requested-With, origin, content-type,');
    header("Access-Control-Allow-Origin: *");
    include("DatabaseConnection.php");
    $sql = $dbh->prepare("SELECT * FROM user_posted_data");
    $sql->execute();
    $row = $sql->fetchAll(PDO::FETCH_ASSOC);
    $terms = array();
    foreach($row as $output) {
        $id=$output['Id'];
        $user_comment = $output['User_comment'];
        $expires_by =$output['Post_expires_by'];
        $expires_by_cleaned = substr($expires_by, 3);
        $expires_by_cleaned_new= substr($expires_by_cleaned, 0, strpos($expires_by_cleaned, 'GMT'));
        $Posted_by = $output['Posted_by'];
        echo"
            <div class='FeedBox' id='FeedBox-".$id."'>
                <img src='img/report.jpg' id='FeedReport-".$id."' alt='Avatar' width='50px' height='50px' style='float:right;'>  
                <img src='img/img_avatar.png' id='FeedImage-".$id."' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
                <div id='FeedHeader-".$id."' class='FeedHeader'>".$Posted_by."</div> <div id='FeedRadius-".$id."'>Within:100 meters</div>
            <div class='UserComment' id='Data-".$id."'>".$user_comment."</div>
            <div id='HelpExpireText-".$id."' style='display:inline-block;'>lend a hand by:</div><div class='DBPostExpireBy' id='DBPostExpireBy-".$id."' style='display:none;'>".$expires_by_cleaned_new."</div><p id='FeedExpire-".$id."' class='FeedExpire' style='display:inline-block;'></p><div class='ReadMore' id='ReadMore-".$id."' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div></div>";
    }

?>

Not sure where i am going wrong please advise

Console.log(deadline) screenshot below

console.log(deadline)

5
  • Try console.log(deadline);. What does that output? Commented Oct 18, 2019 at 11:43
  • Why not just ask about the formatting? This is not a PHP question unless there are errors in the PHP, then it is not a jQuery question Commented Oct 18, 2019 at 11:53
  • Please try $('.FeedExpire').each(function () { var deadline = new Date(this.innerText.trim()).getTime(); Commented Oct 18, 2019 at 11:58
  • @mplungjan tried the above still getting the same output(no changes). Commented Oct 18, 2019 at 12:00
  • @nickbellavi See my updated answer Commented Oct 18, 2019 at 12:49

2 Answers 2

2

Have a look at this. No need to change the PHP, assuming the timestamp is in milliseconds You need to convert the timestamp to an INT

You do NOT want to clear the interval until ALL timers are expired. You could have a timer per post or just keep it running

success: function(data) {
       var results=data;
       $('.Homefeedstart').html(results);
       startTimers():

add this elsewhere in the script outside the ajax

const pad = num => ("0" + num).slice(-2)
const aSecond = 1000;
const aMinute = aSecond * 60
const anHour = aMinute * 60;
const aDay = anHour * 24;
let x;

function startTimers() {
  clearInterval(x)
  x = setInterval(function() {
    $('.DBPostExpireBy').each(function() {
      let deadline = new Date(+$.trim($(this).text())).getTime();
      let now = new Date().getTime();
      let t = deadline - now;
      let days = Math.floor(t / aDay);
      let hours = Math.floor((t % (aDay)) / (anHour));
      let minutes = Math.floor((t % (anHour)) / (aMinute));
      let seconds = Math.floor((t % (aMinute)) / aSecond);
      let time = t < 0 ? "Expired" : days + "d " + pad(hours) + "h " + pad(minutes) + "m " + pad(seconds) + "s "
      $(this).next().html(time);
    });
  }, 1000);
}

startTimers(); // MOVE this to inside the success
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='FeedBox' id='FeedBox-1'>
  <img src='img/report.jpg' id='FeedReport-1' alt='Avatar' width='50px' height='50px' style='float:right;'>
  <img src='img/img_avatar.png' id='FeedImage-1' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
  <div id='FeedHeader1' class='FeedHeader'>Posted_by A</div>
  <div id='FeedRadius-1'>Within:100 meters</div>
  <div class='UserComment' id='Data-1'>User A comment</div>
  <div id='HelpExpireText-1' style='display:inline-block;'>lend a hand by:</div>
  <div class='DBPostExpireBy' id='DBPostExpireBy-1' style='display:none;'>1581501796895</div>
  <p id='FeedExpire-1' class='FeedExpire' style='display:inline-block;'></p>
  <div class='ReadMore' id='ReadMore-1' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div>
</div>
<div class='FeedBox' id='FeedBox-2'>
  <img src='img/report.jpg' id='FeedReport-2' alt='Avatar' width='50px' height='50px' style='float:right;'>
  <img src='img/img_avatar.png' id='FeedImage-2' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
  <div id='FeedHeader1' class='FeedHeader'>Posted_by A</div>
  <div id='FeedRadius-1'>Within:100 meters</div>
  <div class='UserComment' id='Data-1'>User A comment</div>
  <div id='HelpExpireText-1' style='display:inline-block;'>lend a hand by:</div>
  <div class='DBPostExpireBy' id='DBPostExpireBy-1' style='display:none;'>1581501896895</div>
  <p id='FeedExpire-1' class='FeedExpire' style='display:inline-block;'></p>
  <div class='ReadMore' id='ReadMore-1' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes if one of the timestamp expired would cause all the timers to stop .Converting the timestamp(miliseconds) to INT did the trick thanks a lot for the suggestion
Yeah but also please use my script since it is much simpler :)
0

please make sure you that you are getting all the data correctly from the server because the code works when the date is added manually

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<p id="demo"></p>

try to update your php as follow:

<?php
    header('Access-Control-Allow-Headers: X-Requested-With, origin, content-type,');
    header("Access-Control-Allow-Origin: *");
    include("DatabaseConnection.php");
    $sql = $dbh->prepare("SELECT * FROM user_posted_data");
    $sql->execute();
    $row = $sql->fetchAll(PDO::FETCH_ASSOC);
    $terms = array();
    foreach($row as $output) {
        $id=$output['Id'];
        $user_comment = $output['User_comment'];
        $expires_by =$output['Post_expires_by'];
        $expires_by_cleaned = substr($expires_by, 3);
        $expires_by_cleaned_new= substr($expires_by_cleaned, 0, strpos($expires_by_cleaned, 'GMT'));
        $Posted_by = $output['Posted_by'];
        echo"
            <div class='FeedBox' id='FeedBox-".$id."'>
                <img src='img/report.jpg' id='FeedReport-".$id."' alt='Avatar' width='50px' height='50px' style='float:right;'>  
                <img src='img/img_avatar.png' id='FeedImage-".$id."' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
                <div id='FeedHeader-".$id."' class='FeedHeader'>".$Posted_by."</div> <div id='FeedRadius-".$id."'>Within:100 meters</div>
            <div class='UserComment' id='Data-".$id."'>".$user_comment."</div>
            <div id='HelpExpireText-".$id."' style='display:inline-block;'>lend a hand by:</div><div class='DBPostExpireBy' id='DBPostExpireBy-".$id."' style='display:none;'>".$expires_by_cleaned_new."</div><p id='".$id."' class='FeedExpire' style='display:inline-block;'></p><div class='ReadMore' id='ReadMore-".$id."' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div></div>";
    }

?>

and your deadline as:

var deadline = new Date(document.querySelector('#DBPostExpireBy-'+this.id).innerHTML).getTime();

2 Comments

Hi Moneer ,double checked on that too but still doesn't seem to work .Maybe going wrong somewhere in the each function in jquery (But unable to figure it out )
can you mark the answer as the right answer, please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.