0

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?

tadman
  • 208,517
  • 23
  • 234
  • 262
pythonic
  • 20,589
  • 43
  • 136
  • 219
  • This is all in one file? – BurningLights Jul 25 '16 at 22:06
  • Sorry to ask, but why would you send the client time to the server? – Simon Jul 25 '16 at 22:06
  • The JavaScript code will run when the page HTML makes it to the client browser. The POST will happen then, but your code does not pay any attention to the response from that HTTP request. – Pointy Jul 25 '16 at 22:06
  • Yes in one file. And I want to get the client time to the server, because I want the user to see client's time. Not only that but also that time would be stored in database. – pythonic Jul 25 '16 at 22:07
  • @Pointy: I am using jquery. Wouldn't that handle it. I am very new to Ajax/javascript/jquery, so maybe I am wrong. – pythonic Jul 25 '16 at 22:08
  • @pythonic you're verry wrong :) – Marko Mackic Jul 25 '16 at 22:09
  • The way you've written this just won't work, unfortunately. You need a separate PHP URL that response to the POST request with the time, and a callback in JavaScript to update the page. – Pointy Jul 25 '16 at 22:09
  • @Pointy I would really appreciate if you give me a simple example to illustrate your point. – pythonic Jul 25 '16 at 22:10
  • Do try and be more descriptive than "not working". That's like going to the doctor and saying "I'm sick" without any other explanation. – tadman Jul 25 '16 at 22:30
  • @tadman: I've explained it, didn't I. I said, I want to post a variable from Jquery to PHP for the same page. – pythonic Jul 25 '16 at 22:34
  • I've edited your question to remove the ambiguity. When asking a question be sure to state both the goal and the obstacle you've encountered in as specific terms as are relevant. "Doesn't work" is usually a sign you haven't done enough diagnostic work or aren't explaining it clearly enough. – tadman Jul 25 '16 at 22:39
  • @pythonic sorry but if already you have a php page where you update client information for what you need to submit a post for show the date.. print the date and stop :) – Daebak Jul 25 '16 at 22:40
  • Possible duplicate of [How to pass JavaScript variables to PHP?](http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Iceman Jul 25 '16 at 22:47

3 Answers3

1

Here is what you're missing, see what's data returned from server :)

<script type="text/javascript">
$(document).ready(function(){
        var d = new Date();
        var returnFromServer = 
        var dateStr = d.toString()
        $.post(window.location, {
            dateStr: dateStr
        }).success(function(data){
          //this is return from server
          alert(data);
    });
        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>

Anyways you need to split files up , because I think this will return the whole page, and the span with your color :)

Marko Mackic
  • 2,293
  • 1
  • 10
  • 19
1

As other said your have to use 2 file one with the js and other for php, in file.php you can make what you want for example to save in db. I tried to comment the code if you don't understand something feel free to ask.

check the path where you save the file php

file.php

<?php

$result = Array();

if (isset($_POST['action'])) {
    $client_date = new Date();

    // HERE YOU CAN USE FOR SAVE IN DB
    $result ['result_msg'] = 'success';
    $result ['client_date'] = $client_date;
} else {
    $result ['result_msg'] = 'error';
}
echo json_encode($result);

?>

html

$(document).ready(function(){
    $.ajax({        
        type: "POST",
        url: "file.php",
        data: { 
            action : 'what you want'
            // IF YOU WANNA SAVE CLIENT INFORMATION HAVE TO MAKE A FORM AND PASS DATA HERE FOR EXAMPLE CLIENT ID ....
        },
        dataType: 'json'
    }).done (function(result) {
        result = JSON.parse(JSON.stringify(result));
        if (result.result_msg === 'success') {
            console.log(result.client_date); // YOU CAN SHOW IN HTML DIV
        } else {
            console.log('ERROR');
        }

    }).fail(function(result) {

        console.log('ERROR');

    });
});

Cheers!!!

Daebak
  • 409
  • 2
  • 9
  • 1
    cities_result is not defined :) – Marko Mackic Jul 25 '16 at 22:30
  • @MarkoMackic thanks... I pasted from my code for make fast :P – Daebak Jul 25 '16 at 22:33
  • Thanks for the answer. But is not possible at all to have those codes in the same file. I have one php page, for which I am making this, as I want to update text on that page with the client's date/time. – pythonic Jul 25 '16 at 22:36
  • If I understood you have a php file that update the clients information so it's logic that you address the ajax to that file update the client's info and brb with the date response. Or I am in wrong ? – Daebak Jul 25 '16 at 22:48
1

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>
Sunil
  • 155
  • 2
  • 6