XMLHttpRequest to Post HTML Form
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.You can either iterate all input elements or get specific ones by calling document.getElementById()
.
Warning: You have to use encodeURIComponent()
for all names and especially for the values so that possible &
contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");var inputData = encodeURIComponent(input.value);request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData
objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData
object from an existing form and we can send it it directly to XMLHttpRequest
's method send():
var formData = new FormData( document.getElementById("my-form-id") );xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/><script>"use strict";function submitForm(oFormElement){ var xhr = new XMLHttpRequest(); xhr.onload = function(){ alert(xhr.responseText); } xhr.open(oFormElement.method, oFormElement.getAttribute("action")); xhr.send(new FormData(oFormElement)); return false;}</script></head><body><form method="POST" action="post-handler.php" onsubmit="return submitForm(this);" > <input type="text" value="previousValue" name="name"/> <input type="submit" value="Update"/></form></body></html>
This snippet is basic and cannot use GET
. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction
.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) { if (request) { request.abort(); } // setup some local variables var $form = $(this); // let's select and cache all the fields var $inputs = $form.find("input, select, button, textarea"); // serialize the data in the form var serializedData = $form.serialize(); // fire off the request to specific url var request = $.ajax({ url : "URL TO POST FORM", type: "post", data: serializedData }); // callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ }); // callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ }); // callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // reenable the inputs }); // prevent default posting of form event.preventDefault();});