'How to submit a form when page loads using JavaScript?

I know this question has been answered many times but in my case the JavaScript code creates a infinite loop which makes my page load continuously,

<script type="text/javascript">
    window.onload = function(){
        document.getElementById('theForm').submit();
    }
</script>

I also tried the below one and it doesn't work:

<body onload="document.theform.submit()";>

The below code does what I need but it's not perfect:

<script type="text/javascript">
    window.onload = function(){
        document.getElementById('submit_button').click();
        setTimeout(function(){window.stop();},2500);
    }
</script>


Solution 1:[1]

If your goal is execute submit onload only 1 times and then break loop, you must add to form some hidden variable and increase variable on every submit. And then on onload function check with if statement if hidden variable larger then 2 then do not submit anymore.

Solution 2:[2]

Try Below Code

<script type="text/javascript">
   $(document).ready(function(){
       document.theForm.submit();
   });
</script>

Solution 3:[3]

$(document).ready(function() {
  while (1) {
    $("#theForm").submit();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" id="theForm" name="theForm">
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praktiskais Latvietis
Solution 2 Chirag Patel
Solution 3