简体   繁体   中英

HTML Form submit data

I have a form on a remote server I'm trying to submit data to, example below

<html>
<head>
</head>
<form  action="http://www.example.com/post.php"  method="post">
<input type="text" name="input1" value="test1"  />
<input type="text" name="input2" value="test2"  />
<input type="submit" name="send" value="Submit" />
</form>
</body>
</html>

I'm trying to auto submit the data like this

<html>
<head>
</head>
<form  action="http://www.example.com/post.php"  method="post">
<input type="text" name="input1" value="test1"  />
<input type="text" name="input2" value="test2"  />
<script type="text/javascript"> 
 document.forms[0].submit(); 
</script> 
</form>
</body>
</html>

It works fine if the first example didn't have a (name="send") name but when it does have a name nothing submits. My question is how would I go about sending the data with a input button that has a name.

Thank you

Note: The answer turned out to be type="hidden" instead of type="submit" , in which the second does not allow DOM submission while also submitting that input 's value in the GET/POST data. type="hidden" does, and it works here since the button does not need to be physically clicked.


Pick one:

<form name="formname" id="formid" action="http://www.example.com/post.php" method="post">
<input type="text" name="input1" value="test1"  />
<input type="text" name="input2" value="test2"  />
<input type="submit" name="send" value="Submit" />
</form>
<script type="text/javascript">
if (confirm('Ok for "formname", Cancel for "getElementById"')) {
    console.log('document.formname.submit()');
    document.formname.submit();
} else {
    console.log('document.getElementById("formid").submit()');
    document.getElementById('formid').submit();
}
</script> 

http://jsfiddle.net/userdude/EAmwj/3

Your JavaScript code will get executed as soon as the page is loaded. That is why it gets submitted immediately.

You need to wrap the JS code in a function and let an event call it from the page.

You can use a regular button and set the function for the onclick event of a button.


<html>
<head>

<body>
<form  action="http://www.example.com/post.php"  method="post">
<input type="text" name="input1" value="test1"  />
<input type="text" name="input2" value="test2"  />
<input type="button" name="send" value="test2" onclick="doSubmit()"  />

<script type="text/javascript"> 
function doSubmit() {
 document.forms[0].submit(); 
}
</script> 
</form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM