简体   繁体   中英

javascript variable to php variable

I need to assign javascript client Date (examp. - 2012/02/03 16:00:00) to php variable. Any idea how? I was trying to use this lines and changing them in million different ways. But I just cant get it.

Today = new Date();
var date = ????
var date = "<?= $date ?>";

I solved it this way:

<input id="date" type="hidden" name="date">
<script type="text/javascript">
     document.getElementById('date').value = Date();
</script>

But thank you very much all.

Add an input in your form

<input type="hidden" name="clientDate">

if you are using jquery add this to set the client date input when the user submits the form

$(YOUR_FORM_SELECTOR).on("submit", function() {
  $("[name=clientDate]").val(new Date());
});

If you want to go with vanilla javascript follow this answer

This will convert js variable to php variable and php variable to js variable

<script>
function jstophp(){


var javavar=document.getElementById("text").value;  

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar;?>";
}

function phptojs(){

var javavar2 = "<?php 

$phpvar2="I am php variable value";
echo $phpvar2;

?>";
alert(javavar2);
}

</script> 
<body>
<div id="rslt">
</div>


<input type="text" id="text" />
<button onClick="jstophp()" >Convert js to php</button>
<button onClick="phptojs()">Convert php to js</button>

PHP variable will appear here:
<div id="rslt2">
</div>

</body>

Demo: http://ibence.com/new.php

you can't simply assign a javascript variable to a php variable. php runs on the serverside and is executed before javascript.
you can however submit an ajax call with the value of your javascript variable to a php script.
you might wanna have a look at jquery's post function.

$.post("test.php", { yourDate: date } );

in your PHP script you'll be able to access the date with $_POST['yourDate'] you can also use a form and a hidden field as you say in your comment.
in this case you can use (assuming you're using jQuery)

$('#id_of_input').val(date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM