Luis
Luis

Reputation: 31

How to submit a form when load page and when submit form?

If I have this:

<script language="javascript">
  $(document).ready(function() {
    $('#form').submit(function() {
      $.ajax({
	    type: 'POST',
		url: $(this).attr('action'),
		data: $(this).serialize(),

		success: function(data) {
		  $('#result').html(data);
		}
	  })        
	  return false;
    });
  })
</script>
<form name="form" id="form" method="post" action="results.php">
 <input type="text" name="date" id="date" value="2014-11-22">
 <input name="send" type="submit" value="Submit">
</form>

<div id="result"></div>

Which works perfectly, how can I submit it when the page is loaded?

Upvotes: 1

Views: 1914

Answers (2)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(It's submit's the form when the document is ready)

$(document).ready(function(){
    $("#form").submit();
});

To automatic submit your form use:

<script language="javascript">
    $(function(){
        $("form").submit();
    });
</script> 

(But be sure your action is not on the same page!)

EDIT:

So your script should look something like this:

<script language="javascript">
    $(document).ready(function() {

        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),

            success: function(data) {
                $('#result').html(data);
            }
        })        


    })
</script>

Upvotes: 1

alphawow
alphawow

Reputation: 390

Here is solution that works on page load:

 <script language="javascript">
$(document).ready(function() {

  $.ajax({
    type: 'POST',
    url: $('#form').attr('action'),
    data: $('#form').serialize(),

    success: function(data) {
      $('#result').html(data);
    }
  })        

 })

Upvotes: 1

Related Questions