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
).