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

2
  • What structure should the JSON data have? Just {"firstName":"harry", "lastName":"tester", "toEmail":"[email protected]"}? Commented Aug 10, 2009 at 17:15
  • 1
    Yes the data would be in the format you described! thanks for the responses! Commented Aug 10, 2009 at 17:21

3 Answers 3

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
  };
};
Sign up to request clarification or add additional context in comments.

10 Comments

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.
@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":"<img src=0 onerror=alert(1)>" not %3Cimg+src%3D0+onerror%3Dalert%281%29%3E
@liweijian You should go with whatever JSON.stringify returns.
@IanKuca It seems that the post data was encoded by html form not JSON.stringify.
@liweijian you'd need to urldecode the form values first if that's the case
|
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.

9 Comments

Josh, the example on jQuery shows otherwise: Looks more like a standard query-string than like JSON.
You guys are right. I've updated the answer accordingly. Thanks!
This is a good example, however according the title this should be performed using javascript, not a javascript library (like jQuery in this case)
You are, of course, welcome to do it the hard way. Everyone else uses jQuery.
The question asks how to POST data using javascript, not the jquery library. This answers the wrong question.
|
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.

1 Comment

That won't work. A FormData objects do not usefully stringify to JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.