I’m a noobie programmer and I wonder how to properly submit a form with javascript.
I made some test code to show you what I mean:
<?php
if (isset($_POST['message']))
{
echo $_POST['message'];
}
?>
<script>
function formsubmit()
{
document.getElementById('form').submit();
}
</script>
<form id="form" name="form" action="" method="post">
<input id="message" name="message" value="hello world">
<input id="submit" name="submit" type="submit">
</form>
<a href="" onClick="formsubmit()">Click me</a><br/>
<input type="submit" onClick="formsubmit()" value="Click me">
When you push the “submit” button inside the tags – the php code will echo “hello world”.
When submitting the form with JS the values won’t post to the page. What am I doing wrong?
Thanks in advance.
I’ve searched the whole afternoon for a solution, but cause of my lack of knowledge about programming I failed to find it.
Believe it or not, but the main problem lies here:
If a form contains an input element with name (or id) of
submitit will mask the.submit()method of the form element, because.submitwill point to the button instead of the method. Just change it to this:See also: Notes for
form.submit()The smaller problem is here:
An empty anchor will just request the same page again before calling
formsubmit(). Just addhref="#".