Incerteza
Incerteza

Reputation: 34884

Submitting a form (post, NOT ajax) with some additional parameters

I need to perform a non-ajax post by clicking the submit of a form. Before submiting I have to add some additional form parameters. Here is how I do this:

  $("#my_form").on("submit", function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();
    data.push({"name": "extra data1", "value": "extra value 1"});
    var params = $.param(data);
    //what's next?
    //$.post($(this).attr("action"), data: params); // ajax request, I don't need an ajax request
  });

But how do I actually submit the form so it will send not only its parametes, but the additional ones I've added to it as well? Obviously, $(this).submit(); won't do this.

Upvotes: 1

Views: 1438

Answers (3)

naota
naota

Reputation: 4718

You might want to see this SO question : Jquery - Create hidden form element on the fly

In your case, I guess you can do somethig like this to add a hidden input:

$("#my_form").on("submit", function (e) {

   $('<input>').attr({
        type: 'hidden',
        name: 'extra data1',
        value: 'extra value 1'
    }).appendTo($(this));  

});

DEMO:http://jsfiddle.net/naokiota/XyLUV/


Or, you could do the same thing like this:

$("#my_form").on("submit", function (e) {

   $('<input type="hidden" name="extra data1" value="extra value 1">')
   .appendTo($(this));

});

DEMO: http://jsfiddle.net/naokiota/Kkq6F/1/

Hope this helps.

Upvotes: 2

Nebojsa Susic
Nebojsa Susic

Reputation: 1260

You can use hidden inputs for this purpose. Add

<INPUT TYPE='hidden' NAME='param1' VALUE='data1' ID='param1'>

and this will be submitted to php.

You can change value of this fields from jQuery by

$('#param1').value = 'data12';

Upvotes: 2

Quentin
Quentin

Reputation: 943515

Instead of pulling the data out of the form and then manipulating the data structure you get, just add hidden input elements to the form before submitting it.

Upvotes: 0

Related Questions