POST data in JSON format
Not sure if you want jQuery.
var form;form.onsubmit = function (e) { // stop the regular form submission e.preventDefault(); // collect the form data while iterating over the inputs var data = {}; for (var i = 0, ii = form.length; i < ii; ++i) { var input = form[i]; if (input.name) { data[input.name] = input.value; } } // construct an HTTP request var xhr = new XMLHttpRequest(); xhr.open(form.method, form.action, true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); // send the collected data as JSON xhr.send(JSON.stringify(data)); xhr.onloadend = function () { // done };};
Here is an example using jQuery...
<head> <title>Test</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="http://www.json.org/json2.js"></script> <script type="text/javascript"> $(function() { var frm = $(document.myform); var dat = JSON.stringify(frm.serializeArray()); alert("I am about to POST this:\n\n" + dat); $.post( frm.attr("action"), dat, function(data) { alert("Response: " + data); } ); }); </script></head>
The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.
Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:
let data = {};let formdata = new FormData(theform);for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];
and then just xhr.send(JSON.stringify(data));
like in Jan's original answer.