How to submit form without submit button

2019-08-10 06:15发布

问题:

I'm trying to submit form without submit button. I used this code to submit: document.forms['form_id'].submit(); but this code submitin over and over again. I want submit just one time

<form method="POST" id="form_id">
<input type="hidden" id="lan" value="" name="number">
</form>


 <script type="text/javascript">

 document.forms['form_id'].submit();

 </script>

回答1:

the form is submitting it self everytime the javascript is loaded, which is everytime you load the page. The default behavior of a form is to submit to the location you are currently at, if not defined, you are continously submitting the form to the page that has the form and that again submits the form.

If you want this submit only to happen once, when a visitor is (re)directed to this page for instance, you should submit to a different one by using the action attribute of your form.

If you want the submit to happen on te request of a user, wrap your submit in a function that is called by an onclick event on a button, or any other event.

<script>
    function submittheform(){
        document.forms['form_id'].submit();
    }
</script>

<form method="POST" id="form_id" action="someHandlerUrl">
    <input type="hidden" id="lan" value="" name="number"/>
    <input type="button" onclick="submittheform()" value="submit the form"/>
</form>

you could use this script in the PHP building your page;

<?php
if(isset($_POST['number'])){
    $number = $_POST['number'];
    $out = '<h1>The form was submitted</h1>';
}else{
    $out = '
    <h1>The form needs to be submitted</h1>
    <form method="POST" id="form_id">
        <input type="hidden" id="lan" value="" name="number">
    </form>
    <script type="text/javascript">
        document.forms[\'form_id\'].submit();
    </script>
    ';
}

echo $out;

?>

When the form is submitted and the number value is present, it shows a page without the script and form.



回答2:

<form method="POST" action="" id="mailform">
<input type="email" name="mail" placeholder="EMAIL" id="mail">
<div id="sub" onclick="mailsubmit()">Click Me to Submit</div>
</form>
<script type="text/javascript">
function mailsubmit(){
document.getElementById("mailform").submit();
var mailid = document.getElementById("mail").value;
return mailid?alert(mailid):alert("You did not submit your Email");
}
</script>