Javascript : Send JSON Object with Ajax?
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"}));
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']
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>