DigitalJoel

2012/05/05

Posting data from multiple forms

Filed under: javascript, jquery — Tags: , , — digitaljoel @ 6:17 pm

For some reason you want to submit the data from multiple forms in a single click. For this example lets assume the following:

  • You have 2 forms, form1, and form2.
  • When form1 is submitted it should submit only the data in input controls in form1.
  • When form2 is submitted it should submit all of the data in form1 AND all of the data in form2.

Option 1. form1 submits as normal.  form2 contains hidden inputs that mirror form1 and javascript is used in an onchange event for the inputs in form1 to keep the hidden inputs in form2 in sync with form1.  ugh.

Option 2. form1 submits as normal. form2 submits via jquery.  Something like this

$.post( 'where/i/want/to/post/to'
, $('#form1').serialize()+"&"+$('#form2').serialize()
, function( response ) {
// here do something with the response from the form post.
alert( "response is " + response );
}
, "json" );

Because of the serialize calls to each form, we get the data from each. I concatenate them with an ampersand and they come through as one big form. Now I don’t have any messy javascript trying to keep hidden fields in sync etc.

Of course, there are going to be some drawbacks. First, now I am submitting the form via ajax, so if you are stuck on old fashioned html form submits then this may not be the solution for you. Second, if either form is entirely empty then the data you are posting may not be well formed, so you should put some error checking around each of those serialize calls and determine if you should use an ampersand to join them. Third, if you aren’t using jQuery, you will be after this… not sure that’s a drawback since jQuery make javascript usable for someone like me that is used to plain Java programming.

Advertisements

Blog at WordPress.com.