Invoke error jQuery ajax callback from within servlet
java, jquery, servlets
Solution
You have to set a `http status code` of something other than `200` to invoke the error callback in jQuery Ajax. You can set a error staus of `500 (which is for Internal Server Error)` like
catch (Exception e) {
resourceResponse.setProperty(resourceResponse.HTTP_STATUS_CODE, "500");
PrintWriter out = resourceResponse.getWriter();
out.println("error");
out.close();
}
in your `catch` block.
Problem
Within my ajax call if an error is received I have an alert : ``` $.ajax({ url: "myUrl", type: 'POST', dataType : "text", data : ({ json : myJson }), success : function(data) { alert('success'); }, error : function() { alert ('error'); } ``` From within java is it possible to send back to invoke the error callback in jquery if an exception is thrown. So something like : ``` try { PrintWriter out = resourceResponse.getWriter(); out.println("success"); out.close(); } catch (Exception e) { PrintWriter out = resourceResponse.getWriter(); out.println("error"); out.close(); } ``` i.e instead of printing "error" on the response, invoke the 'error' callback within the jQuery code.