0

I'm currently trying to send data from my jsp webpage view to my spring controller by using a Ajax POST json request but for some receiving the controller never seems to receive it. The strange thing is that it works when i use a GET request but since it is valuable data which need to be stored in a database, i would prefer to use POST instead.

The javascript code in my JSP view:

function ajaxEdit(){
            var aData = oTable.fnGetData( iPos );//get data of the clicked row
            var id = aData[0];
            var data = {
                    id : id,
                    name : $('#editName').val(),  
                    email : $('#editEmail').val(), 
                    phoneNumber : $('#editPhoneNumber').val(), 
                    address : $('#editAddress').val(),
                    city : $('#editCity').val(),
                    postalCode : $('#editPostalCode').val(), 
                    funct : $('#editFunction').val(),
                    company : $('#editCompany').val(),
            };
            $.ajax({  
             type : "POST",   
             contentType: "application/json; charset=utf-8",
             url : "ajaxEditPerson.htm",
             dataType: "json",
             data : JSON.stringify(data),
             success : function(response) {  
                 alert(response);
             },  
             error : function(e) {  
                 alert('Error: ' + e);   
                }  
               });  
        }

and my spring controller:

    @RequestMapping(value = "ajaxEditPerson", method=RequestMethod.POST)
public @ResponseBody
String ajaxEditPerson(@RequestBody Person person, HttpServletRequest request){
    System.out.println("received edit request: " + person.toString());
    //Save edited item in database
    personManager.addPerson(person);
    return "okay";
}

What i'm i doing wrong here? The request doesn't seem to reach this method at all since the first print line is never executed. Also the error code alert in the javascript code always gives me this "Error: Object object" error. I've also added the following 2 dependencies to maven:

           <!-- Jackson JSON Mapper -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
       </dependencies>

EDIT:

I have changed the controller method arguments to:

@RequestMapping(value = "ajaxEditPerson", method=RequestMethod.POST)
public @ResponseBody
String ajaxEditPerson(@ModelAttribute("person") Person person, HttpServletRequest request, HttpServletResponse response){
    System.out.println("received edit request: " + person.toString());
    return "okay";
}

The print is now executed, so atleast the request has reached the method for sure. But the data that it included is all NULL and the ajax request also still receives an error reponse instead of a succesfull one....

EDIT2:

I can do both ajax GET and POST requests successfully now but without JSON. For some reason json doesn't seem to work. The corresponding method in the controller can receive the data but says its NULL. Is there anything else i should set up before using json? Something in the configuration files?

EDIT3:

Turned out that i needed to at the following line to my spring configuration :

<mvc:annotation-driven />

Everything is working fine now!

Jonhy
  • 155
  • 2
  • 8

1 Answers1

0

Making this an answer since it wouldn't fit in a comment...

Your @RequestMapping does not include a '.htm', but your URL in the $ajax() call does. I suspect you have a mismatch there. Also, assuming you are running this as a WAR being deployed to a web container, I also do not see the WAR context as part of the request URL on the JavaScript side. I would expect to see something like MyWar/someControllerLevelPath/ajaxEditPerson, where "someControllerLevelPath" is optional but set at the Controller level.

My suggestion would be to use some browser debugger (Chrome's Dev Tools, FireFox's FireBug, IE's Dev Tools) to see what is being sent and the EXACT response/HTTP error code you are getting back. You can use these tools to see what the HTTP request headers look like (this included the request URL in full as well as host and such) as well as the payload/headers being send back. I suspect you will be getting a 404 NOT FOUND based on what I am seeing in your sample code. If that is the case, then your URL mapping is wrong. If you are getting something else, then reply back to this and we can figure it out.

Another suggestion would be to add some System.out.println() statements in your Spring controller and see if your handler method is getting called and determine how far the call is going if it is. It's quite possible your handler is getting called, but failing somewhere. If this is the case, I believe your HTTP response code would be a 500. Another option would be to run your server in an IDE or with remote debug turned on in the JVM and attach to it with a debugger, like Eclipse or NetBeans, then pepper your handler method with break points.

Id's start simple and see what HTTP response code you are getting back first. That can usually tell you a lot by itself.

CodeChimp
  • 8,016
  • 5
  • 41
  • 79
  • Thanks for your reply! But unfortunately it didn't help me so much.. You're right, the RequestMapping and Ajax url don't match but i have set up a internalresourceviewresolver in spring to solve this. Because of this i can leave out the WAR context part and spring will map it automatically to the right controller method. I have just tried out the chrome dev tools like you suggested and watched what happens if i make this request. The status shows "canceled" but the request url is indeed "MyWar/someControllerLevelPath/ajaxEditPerson.htm". Also i already have a printline at start of the method – Jonhy Apr 23 '14 at 12:12
  • Also no response data is available. So seems like the request is sent to the server but no response is received. But in that case wouldn't we get a time out status instead of canceled? – Jonhy Apr 23 '14 at 12:16
  • So, you got an HTTP 206? If not, what is the exact HTTP error/return code you got back? Was there any data in the response body? I am not sure why you jumping through so many hoops to make what seems like a very confusing setup with your request mappings. If you are deploying a single app, why not just use embedded Tomcat/Jetty so that you don't have to worry about the WAR context? Just seems like down the road it would be a nightmare to support since you know have to know there is this intermediate conversion happening. – CodeChimp Apr 23 '14 at 13:04
  • Well actually, i'm developing with a eclipse/maven/tomcat setup and the internalresourceviewresolver in spring is just a simple bean which handles it all for me. It's very easy and worked fine until now... Concerning the HTTP code, the strange thing is that instead of an actual error number the chrome dev tool just showed "canceled"and no response data was available to show. Thats what i meant in my last post, maybe i should have been more clear... – Jonhy Apr 23 '14 at 13:25
  • Take a look at this. Not sure if it applys, as the sample above does not seem to do any of the 3 things it said would trigger a cancel in Chrome: http://stackoverflow.com/questions/12009423/what-does-status-canceled-for-a-resource-mean-in-chrome-developer-tools – CodeChimp Apr 23 '14 at 14:54
  • Thanks for the link! The first point made me thinking since i've a bootstrap modal with a button which calls this Ajax function with the onclick() call.But ofcourse the DOM node gets removed afterwards so that was the reason that the request got canceled! I've now removed the onclick() call and instead made a javascript listener which will call the ajax code. But unfortunately it still has not saved my problem. The http response code is now 200 (OK!) and the response is also the one that my method returns ("okay") but still the ajax error function is executed and my received data is NULL – Jonhy Apr 23 '14 at 15:27
  • json is the only problem left now... check edit 2 :) – Jonhy Apr 23 '14 at 15:44
  • I accepted your answer, since it helped me fix my problems. Thanks :) – Jonhy Apr 23 '14 at 18:04
  • Your getting an error because your return is not valid JSON. You indicate in the AJAX call that the data type is JSON. jQuery will try to convert that to a plain-old-JavaScript object, and will immediately get an error. – CodeChimp Apr 23 '14 at 19:36
  • You're right. I thought the datatype concerned the type of data that i've included in my request to the server instead of the data type of the response that i'm going to receive. I changed it to "text" and don't get any errors now – Jonhy Apr 23 '14 at 20:56