-2

I made a javascript to get date, month, and year of today and it return my date time in "YYYY-MM-DD" Format. I want to get that date and set it in a php variable. How to do that?

Here is my script:

<script>
function date_js($date_js)
{
    var today = new Date();
    var day = today.getDate();
    var mon = today.getMonth()+1;
    var y   = today.getFullYear();

    $result-date=y + "-" + mon + "-" + day;
    return $result-date;
}
</script>

My php code:

<?php
   $date=date_js;
   echo $date;
?>

Is there anyway to get the value of my script in php?

4
  • 1
    JS is executed after PHP. You'll need ajax for that. Commented Jan 14, 2016 at 7:31
  • 3
    Possible duplicate of How to Passing value javascript variable to php? Commented Jan 14, 2016 at 7:32
  • Fire an AJAX request. Commented Jan 14, 2016 at 7:34
  • If you just want current date, get it in php $date = date('Y-m-d'); Commented Jan 14, 2016 at 7:45

2 Answers 2

0

PHP is a server side language which executes before Javascript. So you can use php variable value to javascript variable, but can not use javascript variable value directly to PHP variable

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, why do you pass a variable to a function and never use it? And why is there a function named the same as the param need? This is bad practice and can make great confusions. And yeah the correct way is to make and ajax POST with your variable and in your php code treat the variable like it would come from a form(with $date = $_POST['date'])

$.ajax({
  method: "POST",
  url: "some.php",
  data: { date: myDate}
})
  .done(function( data) {
    alert( "Date Saved: " + data);
  });

As for your php:

<?php

$date = $_POST['date'];
echo $date;

?>

The Ajax post script you can choose to be triggered by leaving the input(blur event) or you can choose to run it after a certain time(1 sec, 2 sec after user stopped typing). Hope it helps, code might not work by just copy paste but this is the way you should go. AJAX->PHP

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.