Passing js variable value hidden as input and then retrieving it using php
I would like to count the number of forms submitted by the user using javascript and then put the number of submitted forms in the hidden input type value attribute and then retrieve that value using PHP (with the hidden input name attribute)
Here is a simple code I tried but it didn't work:
form.html
<form method="post" action="submit.php">
<input type="text" name="name" placeholder="name"/>
<input type="text" name="firstname" placeholder="firstname"/>
<input type="hidden" name="nb_submit" value="" id="nb"/>
<input type="submit" value="OK" onclick="count_nb_submit()"/>
</form>
after completing the html form, I put the javascript code:
<script type="text/javascript">
var nb=0;
function count_nb_submit()
{
nb ++;
return nb;
document.getElementById('nb').value=nb;
}
</script>
submit.php
<?php
echo $_POST["nb_submit"] ;
?>
+3
source to share
4 answers
In your script
you return
ing before you finish your job.
You should only use it return
when you want to stop the function and return the result. Nothing will be read upon return.
This is how your code looks like:
<script type="text/javascript">
var nb=0;
function count_nb_submit() {
nb++;
document.getElementById('nb').value=nb;
return nb;
}
</script>
+3
source to share
JS CODE:
<script type="text/javascript">
var nb = 0;
function count_nb_submit() {
nb++;
var myform = document.getElementById('test');
document.getElementById("nb").value = nb;
myform.submit();
}
</script>
Form CODE:
<form method="post" name="test" action="submit.php" id="test" target="_blank">
<input type="text" name="name" placeholder="name"/>
<input type="text" name="firstname" placeholder="firstname" onblur="count_nb_submit();"/>
<input type="hidden" name="nb_submit" value="0" id="nb"/>
<input type="button" value="OK" onclick="count_nb_submit();" />
</form>
0
source to share
<script type="text/javascript">
var nb = 0;
function count_nb_submit()
{
nb++;
var myform = document.getElementById('test');
document.getElementById("nb").value = nb;
myform.submit();
}
</script>
<form method="post" name="test" action="submit.php" id="test" target="_blank">
<input type="text" name="name" placeholder="name"/>
<input type="text" name="firstname" placeholder="firstname" />
<input type="hidden" name="nb_submit" value="0" id="nb"/>
<input type="button" value="OK" onclick="count_nb_submit();" />
</form>
0
source to share