2
votes

I'm trying to show a succes message after submitting a form. I use jQuery form plugin from link

and submitting works fine. Just like that :

$('#emailForm').ajaxForm();

Now I would like to add a succes message under a submit button, so I added a div below :

<input name="submit" type="submit" value="#springMessage('action.save')" />

                <div id="emailSuccessMessage">

                </div>

and add some changes to the jQuery code :

        var options = { 
        target:        '#emailSuccessMessage',  
        success:       showResponse 

    }; 

$('#emailForm').ajaxForm(options); 

function showResponse(responseText, statusText)  { 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
} 

My Controller method is :

@RequestMapping(value = "/password", method = RequestMethod.POST)
    public String changePassword(@Valid @ModelAttribute("editPassword") EditPasswordForm editPasswordForm, BindingResult result) {
        if (result.hasErrors()) {
            return "editAccount";
        }

        userService.changePassword(editPasswordForm);

        return "editAccount";
    } 

Now when I try to submit, it works but no alert is shown ( I added an alert just to test). How does the showResponse method works? I'm new to jQuery and I would like to know how can I achieve my goal. Where should I set the responseText?

Thank

Dawid

1
it looks like a function showResponse from success is never called.. why?Dawid

1 Answers

2
votes

If you are using ajax with Spring MVC you need to make sure that your response will be within Response Body In ordet to do that add @ResponseBody annotation

So your code should look like:

@RequestMapping(value = "/password", method = RequestMethod.POST)
@ResponseBody
    public String changePassword(@Valid @ModelAttribute("editPassword") EditPasswordForm editPasswordForm, BindingResult result) {
        if (result.hasErrors()) {
            return "editAccount";
        }

        userService.changePassword(editPasswordForm);

        return "editAccount";
    } 

You can read more about that in Spring MVC reference guide: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody