0

Ok so I'm submitting a simple form to my Spring Controller through jQuery. Here is the code:

<form id="addNote" role="form" action="addNote" method="POST">
        <div class="form-group error">
            <label for="note">Enter your Note </label>
            <textarea rows="3" cols="50" name="note" class="form-control"
                id="note"></textarea>
        </div>
        <div class="alert alert-danger" style="display: none">
            <strong>Error!</strong> Text length must not exceed 100 characters
        </div>
        <button type="submit" class="btn btn-default">Save Note</button>

$(document).ready(function(){
    $("#addNote").submit(function(e){
        e.preventDefault();
        var formObj = $(this);
        var formURL = "addNote";
        var formData = $("#note").val();
        $.ajax({
            url: formURL,
            type: 'POST',
            data: formData,
            success: function(response){
                alert(response);
            },
            error: function(response){

            }
        });
    });
});

And the Controller method:

@RequestMapping(value="/addNote", method=RequestMethod.POST)
public Vector<String> addNote(Locale locale, Model model, HttpServletRequest httpServletRequest, HttpSession httpSession){
    String note = httpServletRequest.getParameter("note");
    notes.add(note);
    ModelAndView mv = new ModelAndView("notes");
    mv.addObject("thenotes", notes);
    return notes;
}

I need to return the notes object to the jQuery so that I can display it's data as output. But this is the error I'm getting in the Chrome console:

enter image description here

So apparently there is a problem in the path. I have tried changing var formURL = "addNote"; to var formURL = "assessment/addNote"; in the jQuery but it doesn't work.

But for some reason if I change return value of addNote() function in the Controller to ModelAndViewand return mv then it works but it's not the response in the jQuery I need.

CobaltBabyBear
  • 2,188
  • 6
  • 26
  • 47

1 Answers1

0

First of all You are using AJAX, so You can't return data using modelAndView.You have to return data as xml/json.

In Your javascript code add the following function:

function getContextPath() {
       return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
    }

reference: How do you get the contextPath from JavaScript, the right way?

Then change You formURL to:

var formURL = getContextPath()+"/addNote";

With the above code requests reaches the controller. Within the controller You have to change Your requestMapping a bit:If You want to return some simple message then You can return it as a string(I am not sure whether it is the best way, but this is how I do it)

@RequestMapping(value = "/addNote", produces=MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
        @ResponseBody
        public String showNote(){

            System.out.println("saving note..");

             return "<response>Example</response>";

        }

If You want to return a Vector or java object to JQuery, then the best idea is to use jackson-mapper or some similar library, You can find info easily with google.A simpler(not necessarily better solution) would be to define a method that would create the xml String by looping through the vector, sth like:

<notes>
<note>note1</note>
<note>note2</note>
</notes>

and return it as a String from controller, and then process xml within JQuery.

I also learn spring, so if someone knows a better solution, I will be happy to read it ;-)

Regards, Mikajlo8

EDIT:I Have changed the requestMethod to GET, otherwise You have to deal with CSRF TOKENS.If You want to use POST, is is easy to find on the internet how to deal with csrf tokens.

Community
  • 1
  • 1
Mikajlo8
  • 81
  • 3
  • Thank for the descriptive answer. But it seems the ajax call still can't find the controller in the first place. I can deal with the controller's response afterwards somehow but first it has to find the controller method. I'm still getting the exact same error. – CobaltBabyBear Aug 30 '15 at 17:40
  • I have tested the answer and it works for me.Could You please show the definition of the entire Controller class?Has any of the requests worked with any of the Your controllers-I am asking because I want to make sure that You have configured things corretly.Regards – Mikajlo8 Aug 30 '15 at 17:50
  • OK so I don't know why but now it is giving a 406 Not Acceptable error instead of a 404 one. I guess that means invalid response. – CobaltBabyBear Aug 30 '15 at 18:04
  • Try to print something within the controller, at the beginning of the method body(the method that maps Your request).Then You will know whether the request has reached the controller.Try also changing the method to GET, both in jquery and controller-just for testing purposes.Remember to reload the project.And print out the entire jqeury ajax error like described here:http://stackoverflow.com/questions/1637019/how-to-get-the-jquery-ajax-error-response-text – Mikajlo8 Aug 30 '15 at 18:14