Is it possible to send the contents of a JavaScript variable to PHP when a form is submitted?
asked Dec 15, 2013 at 15:49
Jamus
8854 gold badges12 silver badges28 bronze badges
1 Answer 1
Yes. Just add a javascript callback to the form submit event
<script type="text/javascript">
var myglobalvariable = "myvalue";
onSubmit = function(){
document.myform.myinput.value = myglobalvariable; return true;
}
</script>
<form name="myform" id="myform" method="post" action="index.php" onsubmit="onSubmit();">
<input name="myinput" id="myinput" type="hidden" />
</form>
answered Dec 15, 2013 at 15:51
Armel Larcier
16k7 gold badges70 silver badges89 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Jamus
Awesome, thanks very much! :) How would I access the retrieved data, though?
$_POST['myinput'] doesn't seem to be it :P I can't var_dump on this server.Armel Larcier
The array key is the name of the input in question. In my example, it'll be 'myinput' but your code doesn't show name attributes on inputs. You should add them to retrieve the values from the $_POST supergrobal
Jamus
Gah, I made a typo haha. That's why it wasn't working. Thanks very much once again :)
default