1

Is it possible to send the contents of a JavaScript variable to PHP when a form is submitted?

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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
Gah, I made a typo haha. That's why it wasn't working. Thanks very much once again :)

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.