pythonic pythonic - 4 months ago 7
Javascript Question

How to referesh a php page after reception of post from jquery

I am posting the local time on the client machine to the server using jquery. Besides displaying that local time through php, I would also save it in a database on the server side. To display the client's time correctly, I need to refresh the php page after receiving the post from jquery. How can I do that? Here is the code. I tried to use header("Refresh:0"), but that didn't work.

<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toString()
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
var res = $(data).filter('#divMessage').text();
alert(res);
});
});
</script>

<div id="divMessage">
<?php
$v2 = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
$dstr = $_POST["dateStr"];
$v2 = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v2</span>";
// I need to refresh the page here!
//header("Refresh:0");
}
echo "<span style=\"color:green\">$v2</span>";
?>
</div>

Answer

Your scheme:

  1. Javascript reads client's time
  2. sends client's time to server with AJAX
  3. receives response from server containing client time
  4. displays that response on the page

Why? If you want to display the client's time, why does the server need to be involved.

Besides displaying that local time through php, I would also save it in a database on the server side

I'm also curious about why you want to save client's time in a database, but assuming you have good reason, just do:

  1. Javascript reads client's time
  2. Javascript displays client's time on the page
  3. Send time to server with AJAX.
  4. Server saves it in DB

There is no need to process the response data coming from the server. The client already has that info.

I tried to use header("Refresh:0"), but that didn't work.

It won't work where you tried it because you're setting headers after content has been sent to the browser (blank space, html and javascript precedes your header() call). If you wish for the same php file that displays the html to also respond to AJAX queries, put all the PHP logic on top, with nothing at all before the opening <?php