Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke error jQuery ajax callback from within servlet

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.

like image 550
blue-sky Avatar asked Jun 18 '12 12:06

blue-sky


2 Answers

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.

like image 168
Prasenjit Kumar Nag Avatar answered Oct 16 '22 09:10

Prasenjit Kumar Nag


You have two options:

  1. Handle each error in servlet and wrap error/success details within JSON response, as pointed by Cranio
  2. Use HttpServletResponse to set status code to http 500 (or other error code) and then just handle error callback in jQuery script
like image 2
ŁukaszBachman Avatar answered Oct 16 '22 07:10

ŁukaszBachman