tags:

views:

95

answers:

4

I have a form, and a submit handler in jQuery.

When the user submits the form, I want to modify (add) some parameters to the POST request, before it is despatched from the client to the server.

i.e.

  1. User clicks 'submit'
  2. My jQuery submit hander begins execution...
  3. I create some new key/value pairs and add them to the POST payload

At the moment, it looks like my only options are to use $.post(), or $('form').append('<input type="hidden" name=... value=...');

Thanks for any help.

Edit: I've already attached a submit handler to the form; I'm trying to edit the post vars in between the user clicking the submit button, and the request being sent to the server.

+1  A: 

Attach a submit() handler to the form.

$('form#myForm).submit(myPostHandlingFunction);

Then submit/ do the post from your function. The easiest thing would be to just populate a couple of hidden inputs in the form and then return true to allow the submit to happen if everything looks right.

Tom
I have to create a lot of inputs. My question is: do I use $.post('url', myData); return false; or $('form').append('lost of new hidden inputs'); return true;? Or is there a better way? I'm hoping there's a better way.
aidan
If you have a ton of additional data to pass through, I guess you'd use $.post. You can call $('form#myForm).serialize to get your initial data dictionary and then append to that, then post the data and redirect your user if it's successful. However, if you have a ton of additional data to pass, why? If it's not user input, why not calculate it on the back-end rather than rely on JavaScript?
Tom
A: 

You can hook the click event of the submit button and do your processing there. For the key/value pairs you might try a hidden form element.

Jay
Thanks for the input. I'm already using a $('form').submit(fnuction(){ ... }); I'm trying to determine the best way to modify the POST vars.
aidan
A: 

Use the submit() function on the form to create a callback. If the function returns true, the form will be submitted; if false, the form will not post.

$('#theForm').submit(function() {
    $("#field1").val(newValue1);
    $("#field2").val(newValue2);
    $(this).append(newFormField);
    return true;
});

etc.

keithjgrant
Sounds like this is the best option then. Although I have to dynamically create a lot of hidden inputs.
aidan
+1  A: 

I don't think you can modify the POST vars that way. When a submit handler runs there's no hash of the form data that really exists that you can add to or modify. I think you're right - your only options to $.post() yourself (which I'd recommend) or to append hidden inputs to the form (has the overhead of DOM modification which you don't really need).

boycy
Thanks for your apropos answer!
aidan