Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger a form submission on page load using Jquery

Tags:

jquery

This doesn't seem like it should be too difficult to accomplish, but I'm in a rush and I have been looking for a simple answer. I need to submit a form on page load. This is my AJAX submit function which works fine. I just need to figure out how to trigger it on page load.

Any help is much appreciated!

$("form#seller-agreement-form").submit(function() {  
        // we want to store the values from the form input box, then send via ajax below    
        $.ajax({  
            type: "POST",  
            url: "http://www2.myurl.com/formhandler",  
            data: "email="+ email + "&status=" + status,  
            success: function(){  
                $('form#seller-agreement-form').hide(function(){$('div#output').fadeIn();});  

            }  
        });  
    return false;  
    });
like image 402
Vaughn D. Taylor Avatar asked Dec 14 '11 19:12

Vaughn D. Taylor


2 Answers

if you call $().submit() it triggers the action; $().submit(function) binds a handler to the submit event.

You can skip the submit however and just call the ajax method directly.

$(function() {
  $.ajax({  
      type: "POST",  
      url: "http://www2.myurl.com/formhandler",  
      data: "email="+ email + "&status=" + status,  
      success: function(){  
          $('form#seller-agreement-form').hide(function(){$('div#output').fadeIn();});  

      }  
  });
});
like image 51
Mathletics Avatar answered Oct 12 '22 23:10

Mathletics


To actually submit the form on page load, you would write something like

$(function() {
   $('#seller-agreement-form').submit();
});

But if what you're trying to do is just to perform the same action that you would otherwise have performed when the form was submitted, then perhaps you don't want to submit the form, but only to do this:

function postForm() {
    $.ajax({  
        type: "POST",  
        url: "http://www2.myurl.com/formhandler",  
        data: "email="+ email + "&status=" + status,  
        success: function(){  
            $('form#seller-agreement-form').hide(function(){$('div#output').fadeIn();});  

        }  
    }); 
}

$("form#seller-agreement-form").submit(function() {
    postForm();
    return false;
});

$(function() {
    postForm();
});
like image 20
David Hedlund Avatar answered Oct 13 '22 01:10

David Hedlund