views:

65

answers:

1

I submit a (jsp) form to a Servlet A. Then I handle some logic which would make the submission either a success or a failure. I use jquery's ajaxForm() function to re-direct the user to a different jsp after the Servlet logic is executed. But before this redirection happens I need to show a javascript notification showing whether the submission was successful or not. Can someone tell me how can I do this?

+2  A: 

Use the success callback handler. This will be invoked whenever the servlet has returned a response. You can access the returned resposne as 1st argument in the callback handler. Easiest way would be to let the servlet return a JSON response so that you can access it as a JavaScript object:

$('#formId').ajaxForm({ 
    dataType: 'json',
    success: function(response, status, xhr) {
        if (response.error) {
            alert('Something failed: ' + response.error);
        } else {
            alert('Submit was successful.');
            window.location = 'newpage.jsp';
        }
    }
});

In the servlet you need to return the response something like as:

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
if (submit was not successful) {
    response.getWriter().write("{ error: '" + message + "' }");
} else {
    response.getWriter().write("{ error: false }");
}
BalusC
Thank for the answer. But What I need is slightly different from this. I want to show a different message if the backend operation fails. (Failing refers to a user error) Any idea?
sunnyj
I updated the answer.
BalusC
I tried this out and it perfectly fits my requirement. A big thank you another time!
sunnyj