Home » Javascript » Javascript : Send JSON Object with Ajax?

Javascript : Send JSON Object with Ajax?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

Answers:

@mellamokb
Your answer will generate simple post data key/value pairs using the application/x-www-form-urlencoded mime type

@CIRK

If you want to post JSON you could do this

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

or

(not using jQuery here)

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

Questions:
Answers:

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

And for the php receiving end:

 $_POST['json_name'] 

Leave a Reply

Your email address will not be published. Required fields are marked *