Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass extra variable when submitting a form using jQuery

Tags:

jquery

post

forms

I have a form in which the Submit button does not sit within the <form> tags. The submit button has an click handler to submit the form via jQuery's submit() event. This works perfectly.

However, I need the value of the Submit button to be POST'ed as well. Since the button does not exist within the <form> tags, it is not included in the POST array. Therefore, I need to engineer a way to pass an extra variable when the form is submitted.

Some stipulations on what cannot happen to achieve this include:

  • The Submit button cannot be moved within the <form> tags.
  • It cannot use the jQuery ajax, post, or get methods.
  • It cannot have hidden input fields or submit buttons hidden by CSS.
  • The form must act exactly as if there was a normal Submit button in the form.

I envisioned something like, but obviously this does not work.

$('#admin_form').submit({'variable_name', 'true'});

Anybody have any ideas on how I could achieve this?

like image 282
Michael Irigoyen Avatar asked Feb 23 '11 21:02

Michael Irigoyen


2 Answers

One thing you could do is use the onsubmit attribute to have javascript inject a post field into the form with the value of the submit button right as it is submitted. You'd have to do this with a hidden input field, but you'd only add the input field right after the user clicked the submit button -- so the input field wouldn't exist there from the beginning (hopefully this satisfies your requirements). So something like:

 function submitHandler()
 {
     submitVal = $('#submitButton').val();
     $('#myForm').append("<input type='hidden' name='submitValue' value='"+
                         submitVal+"' />");
     return true;
 }

Which would stick in the extra value right as the button was clicked.

like image 200
Jesse Cohen Avatar answered Nov 19 '22 03:11

Jesse Cohen


This seems to be an old question, but since I just ran into a similar issue and found a good solution (for me), I thought I'd post it:

 $('#admin_form').trigger('submit', [ { 'variable_name': true } ]);

or

$('#admin_form').trigger('submit', [ 'variable_name', 'true' ]);

depending on whether you want to pass a variable called variable_name with value true or you want to pass 2 separate variables.

And just to be clear, this will not of course automatically submit variable_name with the rest of the form fields, but if you have a submit handler, as I do in jQuery, the variables will be passed as arguments, after the event.

like image 23
AsGoodAsItGets Avatar answered Nov 19 '22 03:11

AsGoodAsItGets