Adding POST parameters before submit

JavascriptJqueryForms

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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;
}); 

Solution 2 - Javascript

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

Solution 3 - Javascript

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
        })
    }))
});

Solution 4 - Javascript

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.

Solution 5 - Javascript

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")
    } 
});

Solution 6 - Javascript

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);
}

Solution 7 - Javascript

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
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondfaView Question on Stackoverflow
Solution 1 - JavascriptPim JagerView Answer on Stackoverflow
Solution 2 - JavascriptLuca C.View Answer on Stackoverflow
Solution 3 - JavascriptsonnenhaftView Answer on Stackoverflow
Solution 4 - JavascriptMichał PerłakowskiView Answer on Stackoverflow
Solution 5 - JavascriptJeff LoweryView Answer on Stackoverflow
Solution 6 - JavascriptDiego Fernando Villarroel DiazView Answer on Stackoverflow
Solution 7 - JavascriptBeefjeffView Answer on Stackoverflow