I have this following piece of code:
var request;
if (request) {
request.abort();
}
request = $.ajax({
cache: false,
type: 'POST',
url: 'http://MyServlet:8080/ABC/ResponseServlet',
data: {'data' : JSON.stringify(jsonData)}
});
request.done(function (response, textStatus, jqXHR){
//location.reload();
console.log("Success! ", response);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
'The following error occured: '+
textStatus, errorThrown
);
});
On my servlet, I have the following code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Access-Control-Allow-Origin", request.getHeader("null"));
response.setContentType("application/json");
createView(request, response);
System.out.println("Redirecting...");
response.sendRedirect("http://anotherURL/index.html");
}
However, when I perform the AJAX call, I get the following error:
Line 160 refers to the request.fail() line.
What am I doing wrong?
Alright, I solved this.
Although I couldn't figure out the underline cause of the error, as Quentin suggested, it could be related to some violation of same origin policy even though there were no explicit errors thrown (even on Firefox w/ Firebug).
This is the way I solved my issue:
Before:
Earlier, on the servlet, after processing the request, the servlet's response was to redirect to a different page.
response.sendRedirect("http://myURLThatIWantedToRedirect");
After:
Instead of redirecting to a different page, I simply sent back a response with the URL of the link where I wanted to forward.
PrintWriter out = response.getWriter();
out.write("http://myURLThatIWantedToRedirect");
On the web app, I simply modified the "AJAX success" method to the following (to do the redirecting):
request.done(function (response, textStatus, jqXHR){
console.log("Success! ", response);
window.location.replace(response);
});
And now, this works, I don't get any errors and the page is redirected to the URL I initially wanted.