Form Posting via jQuery

TechBoyJK

Lifer
Oct 17, 2002
16,699
60
91
Thoughts about the best way to submit a form via jQuery?

I'm loading a div via ajax that has a form on it. When someone hits 'submit' on the form, I'm assuming I create an 'onClick' function that disables the submit buttton, gathers the form variables, and submits them via ajax.

Is this the right function to be looking at?

http://api.jquery.com/jQuery.post/
 

wand3r3r

Diamond Member
May 16, 2008
3,180
0
0
You can either override a button, or the form's submit event. Basically either will work and it depends if the form submission button is inside the form or not.
Code:
// Override the button's click event (the button can be located anywhere, even outside the form)
$("#inputButtonId").click(function() {
  
   $.ajax({
       type: 'POST',
       data: { $('#formId').serialize(); }
       success: function (response) {
           // do something with the response
       }
   });

   // Prevent the form from submitting
   return false;
});
Alternatively:
Code:
// Override the form's submit
$("#formId").submit(function() {
  $.ajax({
       type: 'POST',
       data: { $('#formId').serialize(); }
       success: function (response) {
           // do something with the response
       }
   });
});
 

GammaLaser

Member
May 31, 2011
173
0
0
If I remember correctly you will generally want to hook into the submit event of the form (as opposed to a click event of a button) because if the user manages to submit the form without the button (through the keyboard for example) then returning false from the submit event would be the only sure-fire way to catch the event.
 

Dratickon

Junior Member
May 13, 2012
21
0
0
If I remember correctly you will generally want to hook into the submit event of the form (as opposed to a click event of a button) because if the user manages to submit the form without the button (through the keyboard for example) then returning false from the submit event would be the only sure-fire way to catch the event.

Very true, as an errant swipe of the enter key can unintentionally submit the form if you bind it to the click event. Also, the preventDefault() method is what I typically use to prevent/control the form submission, but returning false also works if you understand what it really does and you're sure it's what you want.