I am faced with the task of creating a POST request using AJAX in jQuery. This involves passing an array of objects, which I can achieve with the following code:
var actor = new Array();
for(var i = 1; i <= incr; i++) {
actor.push({
"name": document.getElementById("idAN"+i).value,
"surname": document.getElementById("idAS"+i).value,
"dateborn": document.getElementById("idAB"+i).value,
"gender": document.getElementById("idAG"+i).value,
"movie": datas
});
alert("actorX: " + actor[i-1].surname);
}
$.ajax({
method: 'POST',
dataType: 'json',
data: { actors: actor },
url: 'http://localhost:8080/movies/actors',
success: function (rest) {
alert("actor added");
},
error: function(rest){
alert("actor not added");
}
});
I have tried receiving the data with this Java method, but it doesn't seem to work. Can anyone provide assistance?
@RequestMapping(value = "movies/actors", method = RequestMethod.POST)
public ArrayList<Actor> addActors(@RequestBody Actor[] actors) {...}
After three days of struggling, I managed to resolve this issue with the help from the comments. The resulting Java method is as follows:
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "movies/actors", method = RequestMethod.POST, headers="Accept=application/json")
public @ResponseBody ArrayList<Actor> add (@RequestBody Actor[] actors) {
ArrayList<Actor> json = new ArrayList<Actor>();
for(Actor A : actors) {
System.out.println("Arrivo");
serv.addActor(new Actor(A.getName(), A.getSurname(), A.getBorn(), A.getGender(), A.getMovie()));
System.out.println("nomeAttore" + A.getName());
json.add(A);
}
return json;
}
Furthermore, here is the updated post request:
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(actor),
contentType: "application/json; charset=utf-8",
url: 'http://localhost:8080/movies/actors',
success: function (rest) {
alert("actor added");
},
error: function(rest){
alert("actor not added");
}
});
In particular, I made a change to a parameter value in the SQL query from databorn to born because the naming had to match the getBorn and setBorn methods. It was important for the object's parameter name in the JavaScript array (actor) to be consistent.