3

i wonder how do websites update time dynamically without ajax requests ? what i have is a comment system .

$('#comment').click(function(){

   $.post(url,{
       comment : $(this).siblings('textarea.#comment_content').val();
   },function(data){
           $('#comments').append(data.output);
   },'json'); 

});

PHP

<?php


   //get comment and update into DB

   $output .= '<div class="comment-text">'.$comment_text.'</div>';   //comment entered right now

   $output .='<div class="showTime">'.getTime(time()).'</div>';

/*
  getTime() is a function where time is entered and calculated according to current "time()" and formatted in words

*/
?>

since now the comment is appended how will i change the content inside .showTime without ajax requests ?

UPDATE

I am sending a php time() to javascript for processing but its showing Invalid Date here's whats happening

<div class="tstamp" time="<?php echo strtotime($row['time']) ?>" ></div> //time from database

When i am recieving this via js it shows Invalid Date

var $time = new Date($('.tstamp').attr('time'));
console.log($time);   //console shows error

i also tried these formats but same problem...

D M d Y H:i:s O
d/m/Y H:i:s
d/m/Y H:i:s A

UPDATE multiplied the strtotime with 1000

  • If you are fetching time from the database then you have to use ajax request. Otherwise how will you able to communicate to the server without refreshing the page.? – 웃웃웃웃웃 May 21 '14 at 08:34
  • question is unclear... you can get time in javascript only .. maybe this helps you – Marius.C May 21 '14 at 08:36
  • then how can i do update time ? any alternative ? @웃웃웃웃웃 –  May 21 '14 at 08:37
  • then how can i do update time ? any alternative ? @Marius.C –  May 21 '14 at 08:37
  • Making a new request every minute on every page that has comment system is a bad choice for performance. There are services available for that doing request to every x seconds to their server for you. Bigger sites uses comment times like "X Minutes Ago". You can achieve this with JS. – Canser Yanbakan May 21 '14 at 08:37
  • how can i achieve with js @R.CanserYanbakan –  May 21 '14 at 08:38
  • In theory, when user opens or reloads the page, let's say comments are already loaded with document load; Maybe every comment has a – Canser Yanbakan May 21 '14 at 08:41
  • can u give an example @R.CanserYanbakan with an answer ? –  May 21 '14 at 08:42
  • Ok i will try. Wait for my fiddle. – Canser Yanbakan May 21 '14 at 08:42

4 Answers4

1

If I understood the question correctly then what you could do is get the time/timestamp from ajax once either on page load or when the comment was posted. After that you can use simple javascript to update that time based on the differnce bw timestamp stored iniatially and current timestamp. You can use something like data-time="timestamp" or any other variant to store the initial timestamp.

EDIT: here is the code(just the top off my head)

<script src="jquery.js"></script>
<div data-time="<?php echo time(); ?>">This div will update time every 5 seconds</div>
<script>
jQuery(document).ready(function(){
setInterval(function(){
var now=new Date().getTime();
now=Math.floor(now/1000);   //converting to seconds
var then=parseInt($("div").attr("data-time"));
var diff=now-then;
$("div").html(diff+" seconds ago"); //convert this to minutes etc etc!
},5000);
});
</script>

P.S. You don't need jquery for this though!

SuperNOVA
  • 721
  • 7
  • 15
0

Since you donot want to use ajax again and again you can go for using node.js. Node.js primarily uses socket if it is available which is faster & data transfer is like real time if it isn't then it uses polling. Which is similar to ajax.

You can directly integrate node.js with database system. But if you want to use clearly with php this is a This is a nice tutorial.Alternatively you can look for chat systems built using node.js .

Even i don't think that for a small website this method will be productive.

If you don't prefer using custom commenting system you can go for prebuilt system here. This is a nice tutorial to begin with.

0

I don't know php too much, but I am sure that uou can use javascript to update time. You can store comment time in attribute '';

and then make code that will be invoked periodically and will update all comments.

setInterval(function(){
    //get all .showTime -> read time from attribute -> update value
}, 60000); // 60k to update every minute

If you want to display user friendly times then it could be nice to use http://momentjs.com/ timeago function

Machet
  • 1,090
  • 8
  • 17
0

Okay, here we go:

Sample HTML:

<section id="comments">
    <article id="comment-1" class="comment">
        <div class="user-image">
            <img src="http://lorempixel.com/50/50/cats" />
        </div>
        <div class="user-info">
            <h2>Derp</h2>
            <time datetime="05/21/2014 09:00:52 AM"></time>
        </div>
        <div class="text">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam malesuada vestibulum dui, eget posuere justo vulputate vitae. Sed fringilla nisi eu est ullamcorper, at dictum arcu gravida.
        </div>
    </article>

        <article id="comment-2" class="comment">
        <div class="user-image">
            <img src="http://lorempixel.com/50/50/cats" />
        </div>
        <div class="user-info">
            <h2>Derpina</h2>
            <time datetime="05/19/2014 23:00:24"></time>
        </div>
        <div class="text">
            Quisque sit amet venenatis urna. 
        </div>
    </article>
</section>

Sample CSS:

#comments{

}

#comments .comment{
    position:relative;
    overflow:hidden;
    margin-bottom:20px;
}

#comments .comment .user-image{
    position:relative;
    width:50px;
    height:50px;
    float:left;
    margin-right:10px;
}

#comments .comment .user-info{
    overflow:hidden;
}

#comments .comment .user-info h2{
    font-size:14px;
    margin-top:0;
    float:left;
}

#comments .comment .user-info time{
    font-size:12px;
    float:right;
}

And the JS:

$(function(){
    var $second = 1000;
    var $minute = $second * 60;
    var $hour = $minute * 60;
    var $day = $hour * 24;

    setInterval(function(){
        $('.comment').each(function(){
            var $this = $(this);
            var $time = new Date($this.find('time').attr('datetime'));
            var $now = new Date();

            var $distance = $now - $time;

            var $days = Math.floor($distance / $day);
            var $hours = Math.floor(($distance % $day) / $hour);
            var $minutes = Math.floor(($distance % $hour) / $minute);
            var $seconds = Math.floor(($distance % $minute) / $second);

            var $time_string = '';

            if($days > 0) {
                $time_string = $time_string + $days + ' Day(s) ';
            }

            if($hours > 0) {
                $time_string = $time_string + $hours + ' Hour(s) ';
            }

            if($minutes > 0) {
                $time_string = $time_string + $minutes + ' Minute(s) ';
            }

            if($seconds > 0) {
                $time_string = $time_string + $seconds + ' Second(s)';
            }

            $this.find('time').text($time_string);
        });
    }, 1000);
});

Working Example:

http://jsfiddle.net/d4Jp7/

Thanks to:

https://stackoverflow.com/a/9335296/339205

Community
  • 1
  • 1
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
  • 1
    if i have a from mysql `datetime` how i am going to format it to be interpreted by javascript @R.CanserYanbakan –  May 21 '14 at 17:17
  • You asked for this and get my answer. I'v spend my time for you and you are asking more questions. Really funny. – Canser Yanbakan May 21 '14 at 17:57
  • hey your answer is *correct* but **incomplete** .since i am sending the `time()` from php i am getting `Invalid Date` in `console.log($time)` see update! @R.CanserYanbakan –  May 21 '14 at 18:10