Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 536
Pol Lepel Avatar asked Nov 30 '25 20:11

Pol Lepel


2 Answers

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="#".

like image 79
Ja͢ck Avatar answered Dec 02 '25 08:12

Ja͢ck


The problem here is that the id and name of the input element on your form is called submit.

This will mask the submit function for the form. Change the name and id and you will be able to use javascript to submit the form.

like image 31
timc Avatar answered Dec 02 '25 08:12

timc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!