Javascript : Send JSON Object with Ajax? - javascript

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.

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>

Adding Json.stringfy around the json that fixed the issue

Related

Ajax send JSON object with two arrays to a servlet and parsing in java servlet without jQuery

I have to send to a servlet two arrays, i use an Ajax POST call that sends a JSON object, and then I have to read the data sent in two lists or arrays in a servlet class in java.
I prefer not to use jQuery for Ajax call.
I am not very familiar with json, i used some code found in stackoverflow and i can't understand if there is a problem in sending or parsing data.
Here is the method to make the Ajax call in Javascript, where cback is the callback function, method = "POST" and url is the url of the servlet:
function makeCall(method, url, from, to, cback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
cback(req)
};
req.open(method, url);
var obj = {};
obj["from"] = from;
obj["to"] = to;
var data = JSON.stringify(obj);
req.send(data);
}
Here is the doPost method in the servlet controller specified by the url. Here is where i found the problem: after doing getParameter, strings json1 and json2 are null:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//...
String json1 = request.getParameter("from");
String json2 = request.getParameter("to");
Gson gson = new Gson();
ArrayList<Double> listFrom = gson.fromJson(json1,
new TypeToken<ArrayList<Categoria>>() {}.getType());
ArrayList<Double> listTo = gson.fromJson(json2,
new TypeToken<ArrayList<Double>>() {}.getType());
//...
}
Your ajax is sending JSON but your servelet is expecting form data, that has JSON in it.
To send the data like your server expects encode each array to JSON and send them as form data
function makeCall(method, url, from, to, cback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
cback(req)
};
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.open(method, url);
var params = new URLSearchParams({to: JSON.stringify(to), from: JSON.stringify(from)});
req.send(params.toString());
}

UTF-8 characters messed up after POST request in ASP.NET Core

I'm using ASP.NET Core MVC.
I'm trying to make a POST request to a Controller with FormData. But, if I put Arabic letters in the FormData to send to the Controller, it receives it as question marks.
I tried changing the Content-Type but then nothing sends at all.
This is how I send the POST request:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'Categories';
}
}
xhr.open("POST", 'http://localhost:52320/api/Categories/Add', true);
const fd = new FormData();
fd.append('CatName', txtCatName.value);
fd.append('FileName', uploadFileName);
xhr.send(fd);
and this is how I receive it in the Controller:
[Route("api/[controller]")]
public class CategoriesController : Controller {
[Route("Add")]
[HttpPost]
public IActionResult Add(FormData formData)
{
if (formData != null && ModelState.IsValid)
{
DataManager.Instance.AddCategory(formData.CatName, formData.FileName);
return Ok();
}
return BadRequest();
}
}
public class FormData
{
public string CatName { get; set; }
public string FileName { get; set; }
}
Solved.
The problem was inserting into SQL, actually. I thought it had been enough to make the column NVARCHAR but apparently I had to use N before the string.
Thanks to everyone in the comments for helping me out! It was useful.

How to pass multiple parameters to #RequestBody using JavaScript XMLHttpRequest

I have that POST method:
function saveSchemaInDatabase(schemaName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName);
}
and i am catching that shoot in my controller in that way:
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName) {
return "redirect:/user";
}
Can someone tell me how i can send multiple params to that controller? For example i want something like that:
//shoot
function saveSchemaInDatabase(schemaName, diagramJson) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName, diagramJson);
}
//catch
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName, #RequestBody String diagramJson) {
return "redirect:/user";
}
I hope you know what i mean. Of course my way doesn't work. Error 400 appears.
Can someone help me? Im done :(
You can crete FormData object and add as many values as you want inside it
var data = new FormData();
data.append("email", "eve.holt#reqres.in");
data.append("password", "pistol");
Then send this formData object to the post request
Like this
xhttp.send(data);

Javascript xhr post body containing two objects as one

I am trying to send two objects to a web api (ASP.NET) , User and House.
Initially, I tried to send them as xhr.send(User,House), but I realized you can only send one object per body.
So, I created a wrapper class to contain both of the objects
public class Wrapper
{
public House house{ get; set; }
public User user{ get; set; }
}
However, when I send the json body into the api, the data receives the data object as null.
What am I doing wrong?
Front End :
var xhr = new XMLHttpRequest();
var url = "api_call";
xhr.open('POST', url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var house = JSON.stringify({address : address, zip : zip});
var user = JSON.stringify({Email: email, Password: "aaaAAA1!"});
var wrapper = JSON.stringify({house : house, user : user});
...
xhr.send(wrapper);
Back End:
public async System.Threading.Tasks.Task<HttpResponseMessage> ApiCall(Wrapper wrapper)
{
// wrapper.house and wrapper.user is null
House house = wrapper.house;
User user= wrapper.user;
...
}
As our conversation as comment,
There is no need to stringify house and user, just stringify wrapper is enough , so initiate house and user to wrapper as object not string, the correction would be something like :
var xhr = new XMLHttpRequest();
var url = "api_call";
xhr.open('POST', url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var wrapper = JSON.stringify({house : {address : address, zip : zip}, user : {Email: email, Password: "aaaAAA1!"}});
...
xhr.send(wrapper);

Unable to POST JSON object from Javascript to a Servlet via AJAX

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");
If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));

Categories

Resources