How to post form variables with javascript, just like a type="submit" button

html, javascript, php

Solution

Believe it or not, but the main problem lies here:

<input id="submit" name="submit" type="submit">

If a form contains an input element with name (or id) of `submit` it will mask the `.submit()` method of the form element, because `.submit` will point to the button instead of the method. Just change it to this:

<input name="go" type="submit">

See also: Notes for `form.submit()`

The smaller problem is here:

<a href="" onClick="formsubmit()">Click me</a><br/>

An empty anchor will just request the same page again before calling `formsubmit()`. Just add `href="#"`.

Problem

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.

Original source