0248881
0248881

Reputation: 771

'Submit' onload enters into a loop

I want this form to submit once the page has loaded, and I've used the following code to do it. The problem is that the page keeps on reloading and stays in that loop.

HTML

<body onload="document.getElementById('filters').submit();">
 <form id="filters" method="post">
  <section>
      <select id="Genre" name="genres" >
        <option value="Select Genre">Select Genre</option>
        <option value="All">All</option>
        {% for row in genre %}
          <option value="{{row.genre}}">{{row.genre}}</option>
        {% endfor %}
      </select>
      <select id="Rating" name="ratings" >
       <option value="Select Rating">Sort by Rating</option>
       <option value="Best">Best</option>
       <option value="Rating_IMDB">IMDB</option>
       <option value="Rating_RT">Rotten Tomatoes</option>
     </select>
  </section>
 </form>
</body>

Upvotes: 0

Views: 717

Answers (2)

thesecretmaster
thesecretmaster

Reputation: 1984

Current State Of The Question

Currently the question doesn't really provide enough information for a good answer, because we have no idea either 1) Where the form is submitted to 2) What the form is supposed to do when submitted

Once these are added, then this answer can be further improved.

Answer

You need to add an action for that form if you want it to do something. Also, I can't see why you want to submit a form BEFORE A USER CAN INPUT ANYTHING.

Currently the form makes no sense. It is acting effectively as a redirect to the page you are already on, because by default action="#" (I think).

AJAX

In order to do the equivelant of submitting a form without this reload loop, you want to use AJAX. This sumbits an asynchronous request to the server and doesn't actually load the page in browser. Here is how:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("POST", "Where_you_are_submitting_form_to", true);
  xhttp.send();
}

source: w3 schools

Upvotes: 3

Gabriel Hobold
Gabriel Hobold

Reputation: 693

You need to put the "action" in the form.

<body onload="document.getElementById('filters').submit();">
<form id="filters" method="post" action="path">
<section>
  <select id="Genre" name="genres">
    <option value="Select Genre">Select Genre</option>
    <option value="All">All</option>
    {% for row in genre %}
    <option value="{{row.genre}}">{{row.genre}}</option>
    {% endfor %}
  </select>
  <select id="Rating" name="ratings">
    <option value="Select Rating">Sort by Rating</option>
    <option value="Best">Best</option>
    <option value="Rating_IMDB">IMDB</option>
    <option value="Rating_RT">Rotten Tomatoes</option>
  </select>
</section>
</form>
</body>

Fiddle

Upvotes: 0

Related Questions