Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Javascript Variable to PHP POST [duplicate]

Tags:

Possible Duplicate:
JavaScript post request like a form submit

I have a value calculated in JS that I'd like to pass as part of an input form to a PHP script. How can I get a value the JS value to the PHP as a POST parameter?

Basically, on submit, I need the total var to be passed via post to the next script.

The first idea that comes to mind is create an invisible input form that has the value in it and is inputted with the form, is that possible?

like image 816
Peter Kazazes Avatar asked Mar 27 '12 01:03

Peter Kazazes


2 Answers

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value=""> 

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php"> <input type="hidden" name="total" id="total" value=""> <a href="#" onclick="setValue();">Click to submit</a> </form> 

Then your javascript something like this:

<script> function setValue(){     document.sampleForm.total.value = 100;     document.forms["sampleForm"].submit(); } </script> 
like image 87
John Petrilli Avatar answered Sep 22 '22 03:09

John Petrilli


Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.

like image 35
joshuahealy Avatar answered Sep 26 '22 03:09

joshuahealy