79

I've this simple form:

<form id="commentForm" method="POST" action="api/comment">
    <input type="text" name="name" title="Your name"/>
    <textarea  cols="40" rows="10" name="comment" title="Enter a comment">
    </textarea>
    <input type="submit" value="Post"/>
    <input type="reset" value="Reset"/>
</form>

I need to add two POST parameters before send to the server:

var params = [
               {
                 name: "url",
                 value: window.location.pathname
               },
               {
                  name: "time",
                  value: new Date().getTime()
               }
             ];

without modifying the form, please.

dfa
  • 114,442
  • 31
  • 189
  • 228
  • 11
    Just a side note: Relying on the user to supply a valid time and url could lead to problems. – merkuro Jun 14 '09 at 21:52

8 Answers8

100

To add that using Jquery:

$('#commentForm').submit(function(){ //listen for submit event
    $.each(params, function(i,param){
        $('<input />').attr('type', 'hidden')
            .attr('name', param.name)
            .attr('value', param.value)
            .appendTo('#commentForm');
    });

    return true;
}); 
dfa
  • 114,442
  • 31
  • 189
  • 228
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
  • 19
    Thats modifying the form – Hontoni Apr 02 '15 at 14:31
  • @Hontoni We can check if the parameter item exists in the form before we append it to the form, that can make the parameter item be appended only once. – guogangj Jan 04 '17 at 06:40
  • 1
    Do you can use `myInput = document.createElement('input')` and then set the attributes as object, like this: `myInput.type = 'text'; myInput.name = 'name'` – Marcelo May 19 '17 at 22:40
  • That's modifying the form. This is the solution IMO: https://stackoverflow.com/a/34566506/9258504 – SamBerk Jun 22 '21 at 15:42
38

you can do this without jQuery:

    var form=document.getElementById('form-id');//retrieve the form as a DOM element

    var input = document.createElement('input');//prepare a new input DOM element
    input.setAttribute('name', inputName);//set the param name
    input.setAttribute('value', inputValue);//set the value
    input.setAttribute('type', inputType)//set the type, like "hidden" or other

    form.appendChild(input);//append the input to the form

    form.submit();//send with added input
Luca C.
  • 11,714
  • 1
  • 86
  • 77
26

Previous answer can be shortened and be more readable.

$('#commentForm').submit(function () {
    $(this).append($.map(params, function (param) {
        return   $('<input>', {
            type: 'hidden',
            name: param.name,
            value: param.value
        })
    }))
});
sonnenhaft
  • 1,638
  • 1
  • 13
  • 15
19

If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:

var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});

$.post("api/comment", formData, function(data) {
  // request has finished, check for errors
  // and then for example redirect to another page
});

See .serializeArray() and $.post() documentation.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
2

You can do a form.serializeArray(), then add name-value pairs before posting:

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
1

Another simple and modern way to do it using vanilla javascript and without modifying the original form is to use the FormData interface:

let form = document.getElementById("commentForm");
form.addEventListener("submit", event => { //add event listener
  let form = event.target;
  let formData = new FormData(form); //create the FormData from the form
  formData.set("url", window.location.pathname); //add the new parameters
  formData.set("time", new Date().getTime());
  fetch(form.action, {method: form.method, body: new URLSearchParams(formData)}); //make the actual request
  event.preventDefault(); //stop the original form from being submitted again, without the new parameters
});

Note 1: in a real application you may want to check if the HTTP request was successful.

Note 2: In the example above I've used the Fetch API to make the request. If you don't want to use it, this is how to make the same request using XMLHttpRequest.

let req = new XMLHttpRequest();
req.open(form.method, form.action, true);
req.send(new URLSearchParams(formData));

Note 3: In both of the examples I've also converted the FormData object to a URLSearchParams object before sending it. This is because this way the object will be sent using the application/x-www-form-urlencoded encoding, which is the same encoding that would have been used by default if the form was submitted the "normal" way. Removing this step will still send the form, but the encoding will be different (multipart/form-data).

ms-afk
  • 13
  • 4
0

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}
-1

You could do an ajax call.

That way, you would be able to populate the POST array yourself through the ajax 'data: ' parameter

var params = {
  url: window.location.pathname,
  time: new Date().getTime(), 
};


$.ajax({
  method: "POST",
  url: "your/script.php",
  data: params
});
Beefjeff
  • 371
  • 4
  • 12