Jakub Zak
Jakub Zak

Reputation: 1232

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.

Upvotes: 0

Views: 3895

Answers (3)

Sudarshan G Hegde
Sudarshan G Hegde

Reputation: 73

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

Upvotes: 0

gpasci
gpasci

Reputation: 1440

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

Upvotes: 1

clem
clem

Reputation: 3366

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);

Upvotes: 0

Related Questions