Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make XmlHttpRequest POST using JSON [duplicate]

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"
   }
}
like image 618
Akshay Khetrapal Avatar asked Sep 15 '16 19:09

Akshay Khetrapal


People also ask

Can JSON be fetched with an XMLHttpRequest?

Despite its name, XHR can be used to fetch data in a form other than XML: JSON, HTML or plain text.

What XMLHttpRequest method must be used to send a POST request to the server?

send() The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.


1 Answers

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" } }));
like image 96
Gilles Quenot Avatar answered Sep 30 '22 23:09

Gilles Quenot