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.
The GET methodsay=Hi&to=Mom appear in the browser address bar when you submit the form. The data is appended to the URL as a series of name/value pairs. After the URL web address has ended, we include a question mark ( ? ) followed by the name/value pairs, each one separated by an ampersand ( & ).
Sending the form data using the 'GET' HTTP method: The GET method is used to request data from specified resources. It sends an empty body to the server and asks to get resources. If the form data is sent using the GET method the data sent by the server is appended to the URL of the page.
The method form. submit() allows to initiate form sending from JavaScript. We can use it to dynamically create and send our own forms to server.
GET: In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful for non-secure data not for sensitive information.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With