POST data in JSON format

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="[email protected]" />

This is the way the post looks now. I need it submit the values in JSON format and do the POST with JavaScript.



Not sure if you want jQuery.

var form;

form.onsubmit = function (e) {
  // stop the regular form submission

  // 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 ( {
      data[] = input.value;

  // construct an HTTP request
  var xhr = new XMLHttpRequest();, form.action, true);
  xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

  // send the collected data as JSON

  xhr.onloadend = function () {
    // done

Here is an example using jQuery...

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

         function(data) {
           alert("Response: " + data);

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.


Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.


Using the new FormData object (and some 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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.