Make XmlHttpRequest POST using JSON

JavascriptJsonAjax

Javascript Problem Overview


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"
   }
}

Javascript Solutions


Solution 1 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAkshay KhetrapalView Question on Stackoverflow
Solution 1 - JavascriptGilles QuenotView Answer on Stackoverflow