1

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.

Incerteza
  • 32,326
  • 47
  • 154
  • 261

3 Answers3

2

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';
Nebojsa Susic
  • 1,220
  • 1
  • 9
  • 12
2

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.

Community
  • 1
  • 1
naota
  • 4,695
  • 1
  • 18
  • 21
0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335