I have some data that I need to convert to JSON format and then POST it with a JavaScript function.
<body onload="javascript:document.myform.submit()"> <form action="" method="post" name="myform"> <input name="firstName" value="harry" /> <input name="lastName" value="tester" /> <input name="toEmail" value="" /> </form> </body> This is the way the post looks now. I need it submit the values in JSON format and do the POST with JavaScript.
23 Answers
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 }; }; 10Here is an example using jQuery...
<head> <title>Test</title> <script type="text/javascript" src=""></script> <script type="text/javascript" src=""></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.
9Using 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.