1

I must create a POST with AJAX request in JQuery, where I must pass an array of objects that I can create with:

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("aggiunto attore");
    },
    error: function(rest){
        alert("non aggiunto attore");
    }
});

I receive the data with this Java method, but this doesn't work. anyone can help me?

@RequestMapping(value = "movies/actors", method = RequestMethod.POST)

public ArrayList<Actor> addActors(@RequestBody Actor[] actors) {...}

After three days of work, i solve this with the help from the comments. This is the result of the method in java:

@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "movies/actors", method = RequestMethod.POST,headers="Accept=application/json")

public @ResponseBody ArrayList<Actor> add (@RequestBody Actor[] actors) {
    //Actor[] actors = actobj.getAllActors();
    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;
}

and this is the 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("aggiunto attore");
    },
    error: function(rest){
        alert("non aggiunto attore");
    }
});

In particular, i changed a value of a parameter in the query sql from databorn to born, because i have the method getBorn and setBorn, the name must be eguals; and eguals must be the name of the object's parameter in the array actor in javascript: born

karthikr
  • 97,368
  • 26
  • 197
  • 188
Federico Peppi
  • 57
  • 1
  • 1
  • 9

2 Answers2

0

Do you get any errors? I think the problem can be that you are not serializing your data to JSON format, try:

data:{ actors: JSON.stringify(actor) }

Also add:

contentType: "application/json; charset=utf-8",

should be ok.

EDIT

try

data: JSON.stringify(actor),
wcislo
  • 1,338
  • 1
  • 9
  • 14
  • I already tried this solution but it seems that's not working, it gives 400 bad request, I think probably because these are not simple objects (actors) but are custom objects – Federico Peppi Jan 14 '16 at 11:00
  • Check eddited answer – wcislo Jan 14 '16 at 11:02
  • i have this response from the console: – Federico Peppi Jan 14 '16 at 11:06
  • Response for preflight has invalid HTTP status code 403 – Federico Peppi Jan 14 '16 at 11:06
  • Failed to load resource: the server responded with a status of 403 (Forbidden) – Federico Peppi Jan 14 '16 at 11:10
  • Sorry, previous comment was probably wrong. I think the problem lays in your security settings, can you edit your post and show spring security config? – wcislo Jan 14 '16 at 11:11
  • Also please tell me what server you are using – wcislo Jan 14 '16 at 11:18
  • I use spring core and spring web resources to create a rest service, the problem is that this difficulty on creating the post message comes out only when I pass an array, with normal objects there are no problems. – Federico Peppi Jan 14 '16 at 11:27
  • Still I would ask you for posting spring-security.xml and telling me what server are you using. – wcislo Jan 14 '16 at 11:42
  • I want to know if you use e.g. Tomcat, Jetty or Glassfish. Do you use spring-boot? Also, do you have spring-security.xml in your webapp/WEB-INF folder? (if you're not using spring-boot) – wcislo Jan 14 '16 at 11:57
  • i use tomcat. yes, the spring-boot – Federico Peppi Jan 14 '16 at 11:58
  • Do you have any security configuration class? Also, is application sending ajax in the same domain as the one receiving it? – wcislo Jan 14 '16 at 12:11
  • I haven't security configuration class and i haven't the same domain for other request AJAX. But if it can help, my AJAX is inside a successfull of an other AJAX – Federico Peppi Jan 14 '16 at 13:13
  • If you don't have the same domain it's probably CORS problem. Try to add annotation on your controller: `@CrossOrigin(origins = "http://localhost:9000")` - remember to change origins value to the domain you are sending ajax from – wcislo Jan 14 '16 at 13:19
  • Try this answer http://stackoverflow.com/questions/31724994/spring-data-rest-and-cors – wcislo Jan 14 '16 at 13:36
  • i tried, but i received: Failed to load resource: the server responded with a status of 400 (Bad Request) – Federico Peppi Jan 14 '16 at 13:44
  • Try to pass data like I wrote above: `data: JSON.stringify(actor),` – wcislo Jan 14 '16 at 13:57
  • i receive 500 internal server error. Is a cycle of errors – Federico Peppi Jan 14 '16 at 14:40
  • Failed to load resource: the server responded with a status of 500 (Internal Server Error) – Federico Peppi Jan 14 '16 at 14:47
  • I meant error from server side console, check your IDE console – wcislo Jan 14 '16 at 14:48
  • Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'dateborn' in 'class it.larusba.serverMovies.bean.Actor'] with root cause. i receive it from cmd – Federico Peppi Jan 14 '16 at 15:00
  • You must create getters and setters on your Actor class on server side in order for deserialization/serialization to work. Also you have to have all of the corresponding fields (name, surname, dateborn, gender, movie) – wcislo Jan 14 '16 at 15:02
  • edit your first post and put your Actor class in there – wcislo Jan 14 '16 at 15:04
  • in order like this? setname,getname,set surname,getsurname... but i believe it's the same have them in order or not – Federico Peppi Jan 14 '16 at 15:04
  • They don't have to be ordered, but for it is case sensitive - if you have field `dateBorn` and getter: `getDateBorn()`, in your ajax request it must be `dateBorn` – wcislo Jan 14 '16 at 15:06
  • it function!!!!!!!!!!!!!!!!!!!!!!!!!!!! thaaaaaaaaaaank you soooo much. 3 days of work for it.. – Federico Peppi Jan 14 '16 at 15:21
  • It would be nice if you could edit post and write what you did to make it work – wcislo Jan 14 '16 at 15:23
0

How about changing

@RequestMapping(value = "movies/actors", method = RequestMethod.POST)

to

@RequestMapping(value = "movies/actors", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)

jackson dependency must be added for this, if it is a maven project try add following as dependencies.

 <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-hibernate4</artifactId>
      <version>2.6.1</version>
    </dependency>