Thursday, June 7, 2012

Submit a HTML Form Using JavaScript



Normally we submit a HTML form by pressing a button. Sometimes we may need to submit thr form using JavaScript, for example online exam timer.

Example code: test_timer.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<SCRIPT LANGUAGE="JavaScript"><!--
setTimeout('document.test.submit()',10000);
//--></SCRIPT>

</head>

<body>
<form name="test" id="form1" method="post" action="test_timer3.php">
  <p>
    <input name="pattern" type="text" id="pattern" />
    <input name="show" type="hidden" id="show" value="quickref" />
  </p>
  <p><input type="submit" name="SubmitForm" value="Submit Form" />
&nbsp;  </p>
</form>
</body>
</html>

test_timer3.php in action:
<?php 

echo $_POST['SubmitForm'];
echo isset($_POST['SubmitForm']);
echo 'The form is submitted! '.$_POST['pattern'];
?>

When you type you, after 10 seconds, the result: "The form is submitted! you" is produced.

Note:
1) when using JavaScript submits a form, $_POST['SubmitForm'] is not set.
2) The form name can not be "submit," i.e <input type="submit" name="submit" value="Submit Form" />
will cause JavaScript  document.test.submit()' confused.

No comments:

Post a Comment