Javascript : Send JSON Object with Ajax?

Adam Halasz picture Adam Halasz · Jun 21, 2011 · Viewed 295.8k times · Source

Is this possible?

xmlHttp.send({
    "test" : "1",
    "test2" : "2",
});

Maybe with: a header with content type : application/json?:

xmlHttp.setRequestHeader('Content-Type', 'application/json')

Otherwise I can use:

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

and then JSON.stringify the JSON object and send it in a parameter, but it would be cool to send it in this way if it's possible.

Answer

Nathan Romano picture Nathan Romano · Jun 21, 2011

With jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

Without jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));