138

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. Commented Sep 15, 2016 at 20:06

1 Answer 1

345

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

10 Comments

not working for me :(
@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"
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...
charset=UTF-8 is unnecessary because it is the default encoding/charset for the application/json type
This doesn't seem to actually send the post body for me...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.