148

Is there a way to use javascript and JQuery to add some additional fields to be sent from a HTTP form using POST?

I mean:

<form action="somewhere" method="POST" id="form">
  <input type="submit" name="submit" value="Send" />
</form>

<script type="text/javascript">
  $("#form").submit( function(eventObj) {
    // I want to add a field "field" with value "value" here
    // to the POST data

    return true;
  });
</script>
hernanvicente
  • 914
  • 8
  • 18
Spook
  • 25,318
  • 18
  • 90
  • 167
  • 2
    possible duplicate of [jQuery - add additional parameters on submit (NOT ajax)](http://stackoverflow.com/questions/2530635/jquery-add-additional-parameters-on-submit-not-ajax) – Marijn Mar 25 '14 at 13:01

7 Answers7

208

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });
molasses
  • 55
  • 6
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 45
    `.appendTo(this)` would probably be better. – jcuenod Jun 12 '15 at 10:37
  • 5
    @jcuenod original `appendTo('#form')` is much better, because such approach allows submit another form with values from this one. – Andremoniy Oct 19 '15 at 14:39
  • 10
    You'll have to add some extra logic to avoid accumulating these input with each submit. – amos Nov 18 '16 at 14:09
  • 3
    You'll probably want to remove the input element before you add it in case it already exists `$(this).find("input[name="+"something"+"]").remove();` – K Vij Jun 04 '20 at 04:50
  • 1
    If it's not AJAX the form and the appended field is gone on submission. – ed22 Apr 08 '22 at 16:30
63

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});
user664833
  • 18,397
  • 19
  • 91
  • 140
Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
  • I need to add a file field dynamically. I tried having type=file, and the value also as the file (I'm using WebKitDirectory, so I actually get the file objects), however it never seems to pass it. The input text always gets passed though. Please help me out! – Swaathi Kakarla Apr 08 '15 at 10:40
  • 1
    My preferred answer due to using `this` instead of the redundant `#form` – rinogo Apr 30 '15 at 16:34
18
$('#form').append('<input type="text" value="'+yourValue+'" />');
de_nuit
  • 650
  • 7
  • 13
13

You can add a hidden input with whatever value you need to send:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});
user664833
  • 18,397
  • 19
  • 91
  • 140
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
11

This works:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});
Jeff Lowery
  • 2,492
  • 2
  • 32
  • 40
11

May be useful for some:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

Mohamed Allal
  • 17,920
  • 5
  • 94
  • 97
  • It is a timesaver. I checked it with a simple form. It works! – TuralAsgar Feb 03 '22 at 14:04
  • 1
    Careful when removing inputs with the same name in a form with radios and checkboxes because uncecked fields may remove checked ones – xtian Apr 30 '22 at 13:51
-2

Expanding upon Khawer's answer, you could refrain from using jQuery - for consistency, eg.
<input type="hidden" name="field_name" value="value" />

asciidude
  • 272
  • 1
  • 3
  • 19