91

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="https://www.test.net/Services/RegistrationService.svc/InviteNewContact" method="post" name="myform">
  <input name="firstName" value="harry" />
  <input name="lastName" value="tester" />
  <input name="toEmail" value="testtest@test.com" />
</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.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
  • What structure should the JSON data have? Just `{"firstName":"harry", "lastName":"tester", "toEmail":"testtest@test.com"}`? – Gumbo Aug 10 '09 at 17:15
  • 1
    Yes the data would be in the format you described! thanks for the responses! –  Aug 10 '09 at 17:21

3 Answers3

178

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
  };
};
J. K.
  • 8,268
  • 1
  • 36
  • 35
  • 65
    I think this is a good, clean, concise example of how to get the job done in 20 lines of code, without 100K of framework. – spidee Nov 16 '12 at 16:36
  • 1
    @IanKuca Thanks:) I was wondering if we can send the json data without urlencode the data? I mean I want to send data like `"cmd":""` not `%3Cimg+src%3D0+onerror%3Dalert%281%29%3E` – alwaysday1 May 03 '13 at 01:45
  • 2
    @liweijian You should go with whatever `JSON.stringify` returns. – J. K. May 08 '13 at 08:54
  • 2
    @IanKuca It seems that the post data was encoded by `html form` not `JSON.stringify`. – alwaysday1 May 08 '13 at 08:57
  • @liweijian you'd need to urldecode the form values first if that's the case – Kevin Peno Aug 28 '15 at 22:21
  • There is no jQuery tag in this question. – Michał Perłakowski Dec 29 '15 at 20:23
  • Help Needed---> . http://stackoverflow.com/questions/43673006/javascript-post-request-as-json – Anuj Balan Apr 28 '17 at 07:03
  • Does the request header have content type json? Because am doing the same and the content type is getting set as `application/x-www-form-urlencoded` and my call breaks as the server expects json. How to resolve that? – Anuj Balan Apr 28 '17 at 14:31
  • How would one attach this code to the actual html form? It would be helpful to add the basic html that can use the above code. – blissweb Jun 22 '20 at 02:56
  • `onloadend` should probably be put before `.send()`, it's unlikely that will cause issues. But, in general it's a good idea to put your event handlers *before* the code that fires the event that uses those handlers. – Chris Hayes Aug 17 '20 at 15:09
29

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.

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
3

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.

c-x-berger
  • 991
  • 12
  • 30
Felk
  • 7,720
  • 2
  • 35
  • 65