2

my ajax code is:

 xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.status);
        if (xhr.status == 200) {
            alert("200");               
        }
        else if (xhr.status == 8001) {
            alert("8001");               
        }
        else if (xhr.status == 8000) {
            alert("8000");             
        }
        else if (xhr.status == 7000) {
            alert("7000");                
        }
        else {
            alert("x");              
        }
    }
};
xhr.open("POST","URL",true);
xhr.send(null);

and my code in page that i addressed in xhr.open is:

    if (request.getSession().getAttribute("SATI_UID") == null) {
        response.sendError(8000);
    } else {
            response.sendError(8001);
    }

it works in firefox and chrome and ie but in safari i always get status 200. i use safari 5.1.7. i also use response.setStatus instead of response.sendError but it's not working. anybody knows why this happens?

behnam27
  • 241
  • 2
  • 4
  • 11

2 Answers2

3

You need to set the status of the response server side, on your servlet.

The AJAX client will get the response and store the status code on xhr.status.

It is supposed to be a valid HTTP status code.

Don't forget the response code has to be set before the response is commited and any headers are sent.

You might want to use HttpServletResponse#setStatus or HttpServletResponse#sendError to do so.

Or you may want to define an error page on your web.xml instead. Check out: How to set HTTP status code in JSP error handlers

Community
  • 1
  • 1
NotGaeL
  • 8,344
  • 5
  • 40
  • 70
1

I think this is because you use non standard http statutes. You should throw an error of the right type 4xx or 5xx (see http status codes) because this code has a real signification in the HTTP protocol, and then in the body of the response set your own custom code for your error.

To sum up, the status code of the http response shouldn't be used to send your own status code because it breaks the protocol and can lead to some problem with middleware servers (like caching servers for instance).

Community
  • 1
  • 1
Gnucki
  • 5,043
  • 2
  • 29
  • 44