Adding POST parameters before submit
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;
});
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
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
})
}))
});
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.