pythonic pythonic - 4 months ago 7
jQuery Question

Passing of variable from Jquery to PHP

I am trying to get the server show the client's date and time, but that is not showing the correct output. Here is the relevant part of the code:

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

<div id="divMessage">
<?php
$dstr = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
$dstr = $_POST["dateStr"];
$v = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v</span>";
?>
</div>


If the code is correct, I should see
"current date time is <client's date/time>"
, but instead I see
"current date time is nothing!"
. What mistake am I doing here?

Answer

Hope this helps, there were several things you needed to add to make it work.

Checking if the page was submitted via post and then parsing the response for the message to redisplay it.

<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();
        //console.log(res);
        $('#divMessage').replaceWith(res);
    });

});
</script>


<div id="divMessage">
<?php
    //include "simple_html_dom.php";
    //$html = new simple_html_dom();
    //$html->load_file('index2.php');
    //$v = $html->find('div[id=box]', 0)->plaintext;

    if (!empty($_POST['dateStr'])) {
        $dstr = '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>";
    }
?>
</div>