March 27, 2012

show server time using php and jquery ajax

Question by Shrestha Sunil

I was trying to show the date and time of server using php and jquery ajax. following are the jquery script to show datetime

<script type= "text/javascript" src="jquery-1.4.1.min.js"> </script>
    <script type= "text/javascript">
$(document).ready(function() {
function update() {
  $.ajax({
   type: 'POST',
  url: 'datetime.php',
  timeout: 1000,
  success: function(data) {
      $("#timer").html(''); 
    window.setTimeout(update, 1000);
   },
  });
 }
});

</script>

<div id="timer"> </div>

following are php script for datetime.php

 <?php

  $msg = date('d/m/Y h:i:s');
  echo $msg;

 ?>

I don’t what is going wrong. It’s not showing output. Any help

Answer by Starx

You have almost got it. Just update this line

$("#timer").html(data); 

Usage:

$(document).ready(function() {

    function update() {
      $.ajax({
       type: 'POST',
       url: 'datetime.php',
       timeout: 1000,
       success: function(data) {
          $("#timer").html(data); 
          window.setTimeout(update, 1000);
       },
      });
     }
     update();

});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!