Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-Submit Form using JavaScript

Tags:

<form name="myForm" id="myForm" action="test.php" method="POST">   <p>   <input name="test" value="test" />   </p>   <p>     <input type="submit" name="submit" value="Submit" />   </p> </form>      <script>      var auto_refresh = setInterval(     function()     {     submitform();     }, 10000);      function submitform()     {       alert('test');       document.myForm.submit();     }     </script> 

I'm having trouble trying to auto-submit a form every 10 seconds once landed on a page. The form name is myForm action="test.php". I get the 'test' message but the page doesn't submit the form.

Any solutions besides autoloading the function upon page load?

FIXED: Removed (name="submit") from the submit button and it worked smoothly.

like image 606
Crys Ex Avatar asked Sep 11 '12 18:09

Crys Ex


People also ask

Can I use JavaScript to submit a form?

Generally, a form is submitted when the user presses a submit button. However, sometimes, you may need to submit the form programmatically using JavaScript. JavaScript provides the form object that contains the submit() method. Use the 'id' of the form to get the form object.

How do you submit in JavaScript?

In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked.


2 Answers

You need to specify a frame, a target otherwise your script will vanish on first submit!

Change document.myForm with document.forms["myForm"]:

<form name="myForm" id="myForm" target="_myFrame" action="test.php" method="POST">     <p>         <input name="test" value="test" />     </p>     <p>         <input type="submit" value="Submit" />     </p> </form>  <script type="text/javascript">     window.onload=function(){         var auto = setTimeout(function(){ autoRefresh(); }, 100);          function submitform(){           alert('test');           document.forms["myForm"].submit();         }          function autoRefresh(){            clearTimeout(auto);            auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);         }     } </script> 
like image 117
Mihai Iorga Avatar answered Sep 29 '22 13:09

Mihai Iorga


Try using document.getElementById("myForm") instead of document.myForm.

<script> var auto_refresh = setInterval(function() { submitform(); }, 10000);  function submitform() {   alert('test');   document.getElementById("myForm").submit(); } </script> 
like image 21
jrummell Avatar answered Sep 29 '22 14:09

jrummell