Javascript : Send JSON Object with Ajax?
Solution 1
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"}));
Solution 2
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']
Solution 3
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
Solution 4
Adding Json.stringfy
around the json that fixed the issue
Related videos on Youtube
Adam Halasz
Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework
Updated on October 15, 2020Comments
-
Adam Halasz over 3 years
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. -
Adam Halasz almost 13 yearsbut man I can use content-type:
application/x-www-form-urlencoded
too if I use stringify, then what's the point to useapplication/json
? :) -
mellamokb almost 13 years@CIRK: What's it matter? The content-type setting is completely arbitrary unless the server treats the one or the other specially. It's just data flowing back and forth at the end of the day.
-
Nathan Romano almost 13 yearswell if your post body is expected to be JSON eg ({name:"John",time:"2pm"}) use content type application/json if your post body is form urlencoded data (name=John&time=2pm) use application/x-www-form-urlencoded
-
Aaron Liu almost 9 yearswhere should I put the URL?
-
Shanimal over 8 yearsThe content-type header is required for some backends. The resource controllers in Spring for example fail if the "Consumes" meta specifies application/json. You can also set responseType if "Produces" meta is set on the method.
-
rohitsakala about 8 yearsCan't use it directly ?
-
Fordi over 7 yearsI don't think this answers the question asked. I believe the dev wants to send a blob of JSON to PHP as Content-Type: application/json, not wrapped in a urlencoded wrapper.
-
Nil over 7 years@ShuruiLiu a URL goes in place of
"/json-handler"
as a 2nd param of theopen()
method -
Anuj Balan about 7 yearsHelp Needed---> . stackoverflow.com/questions/43673006/…
-
Wilt over 6 yearsI like the "not using jQuery example" showing that using JQuery is totally redundant.
-
David over 6 yearsThis is not really sending JSON over, it is sending formdata over. You can also send JSON directly, in which case you can not read it with $_POST, but instead read it with json_decode(file_get_contents('php://input'));
-
Rajib over 6 yearshow can retrieve the data in receiving end
-
Ankit Parmar over 5 yearsHi Nathan, Can we get the success callback in post method?
-
Robert about 5 yearsDear friends can you share this POST ajax with the entire needed code to be used on the page? Or thank you as well if you have a kind link to some full working example of vanilla ajax POST with JSON