135

How can I make an AJAX POST request sending JSON data using vanilla JS.

I understand the content-type is url form encoded and it doesn't support nested JSONs.

Is there any way I can make such a POST request using nested JSON in plain old JS. I've tried the various serialize methods found here on SO but they all flatten my JSON into one format.

Here's my JSON:

{
   email: "[email protected]",
   response: {
       name: "Tester"
   }
}
1
  • 1
    Your question does not contain valid JSON. Perhaps you are sending this JavaScript object, which is then converted to JSON through some process? Either way, as has been said by others in the comments to the below answer, there isn't any reason why your JSON object should be flattened. If you are having issues with a specific library or block of code, post that instead. Sep 15, 2016 at 20:06

1 Answer 1

339

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
10
  • 7
    not working for me :(
    – markroxor
    Sep 2, 2018 at 11:53
  • 1
    @BillalBegueradj, his target URL is "/json-handler", a relative path to the domain where the call is being made. May be the name is a bit confusing, it happened the same to me... Just change it for "someFolderNameHere"
    – Arampg
    Nov 19, 2018 at 17:23
  • 4
    Note that this only works for "POST" and "PUT" requests. If you are using a "GET" request, the argument to of xmlhttp.send([argument]) will be ignored. I wound up changing an AWS API Gateway endpoint resource to "PUT" to get around this issue... Mar 4, 2019 at 18:25
  • 4
    charset=UTF-8 is unnecessary because it is the default encoding/charset for the application/json type
    – user2188550
    Aug 9, 2019 at 16:05
  • 1
    This doesn't seem to actually send the post body for me...
    – Tyguy7
    Nov 14, 2019 at 16:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.