I want to know how can I handle errors using jquery $post from Struts2 action result.
For example in my strut2.xml I have handled the error using the following:
<action name="helloWorld" class="net.roseindia.Struts2HelloWorld">
<result="success">/pages/HelloWorld.jsp</result>
<result="error">/pages/HelloWorld.jsp</result>
</action>
In my jquery call, I have the following:
$.post("helloWorld", function(){
}).success(result){
$("#div").html(result);
}).error(){
alert("ERROR");
};
Even if the result is equal to error, it always goes to success.
So how can I make the result=”error” go to $.post error in my jquery call?
it is “success” because regardless of what “comes back” you will have an AJAX successful request/response. What you’ll need to do is set some “failure” notice from the servlet and then examine what comes back in the “success” block.
“success” means the request returned a “2xx” code. “error” means a non-2xx success:
more on html codes here : http://www.w3.org/Protocols/HTTP/HTRESP.html
So like something like this (not useful code but you’ll get the idea)
Edit: Below Anthony made a comment that since the user is in control of the service / page being requested – you can build the servlet / code in a way to return an html error code rather than interrogating the resulted html – this is a great suggestion. Thank you Anthony