I have written piece of code, below is the code
<script type="text/javascript">
function submitform()
{
document.myform.action='http://mysite/index.php';
document.myform.submit();
}
</script>
<?php
if(isset($_POST['submit_details']))
{
echo "<script typ=javascript> submitform();</script>";
}
?>
<form id="myform">
------
------
<input type="submit" name="submit_details">
</form>
when i try to submit the form , it gives me error document.myform is undefined, how to solve this error
4 Answers 4
document.myForm is undefined when you are calling the script because it is being run before the form element has been received by the browser. You need to put the script after the form tag, or use a document.onload event handler (or similar).
(Although quite why you want to automatically and immediately submit a form by JS without your user doing anything is beyond me.)
Comments
If that's literally your code, then it's got syntax errors up the wazoo.
Try:
<?php if (isset($_POST['submit_details'])) { ?>
<script type="text/javascript">submitForm();</script>
<?php } ?>
1 Comment
Try moving the script to the bottom of the page, or better, listen to the window.onload event. When the script is loaded by the browser, the DOM hasn't finished loading and cannot find document.myForm yet.
Comments
Why dont you just put the javascript submit inside the input like so?
<input type="submit" name="submitdetails" onclick="javascript:submitform();" />
Then use $post with jquery to run the page.
5 Comments
javascript: is superfluous.javascript: inside on* attributes of elements. Suggesting he add jQuery to his page is overkill - why include a whole JS library to do something simple that can be done in a quick, easy, cross-browser manner?onclick attribute is not a URL, so you don't need the javascript protocol. <input onclick="submitform()"> is just fine. Not that the OP needs javascript -- they could just put the action in the form.
<form action="http://mysite/index.php" method="GET">and if this is index.php, then your PHP will automatically submit the form again... and again... and again...