Issue
An ajax call to servletA. servletA needs to redirect or forward to another content page. Is it possible.? I am seeing response for redirect in Ajax done function rather going to redirected content page. May be I am missing some thing vital but do not know. I was trying to redirect to another content page in aem servlet. It is returning 200 OK response in network tab but NEVER goes to the specified redirect page.
My colleague said with an Ajax call redirect is not possible as it is separate thread request, is it? I was under assumption if I say response. Sendredirect(); A new request will be made and response will be loaded on the browser window.
@Component(
immediate = true,
service = Servlet.class,
property = {
"sling.servlet.paths=/bin/test/redirect"
})
public class TestRedirectServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 3591693830449607948L;
@Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) {
PrintWriter writer = null;
try {
writer = response.getWriter();
// final RequestDispatcherOptions options = new RequestDispatcherOptions();
// final SlingHttpServletRequest syntheticRequest = new SyntheticSlingHttpServletGetRequest(request);
// request.getRequestDispatcher("/content/<project-name>/en_US.html", options).forward(syntheticRequest, response);
// return;
response.sendRedirect("/content/test-site/sample.html");
} catch(Exception e) {
} finally {
if (writer != null) {
writer.print("done");
writer.flush();
writer.close();
}
}
}
}
Solution
By using response.sendRedirect("/content/test-site/sample.html");
you are essentially sending back an HTTP 301 or 302 redirect to you AJAX request. If this request was initiated via browser navigation, the window would redirect, but since the redirect is initiated by AJAX, the response will simply not contain a successful HTTP 200 status code, and AJAX will consider this a failure which would likely trigger your error
function callback.
More on HTTP Status Codes.
As mentioned, you could use your servlet's print writer to return a JSON response as opposed to a redirect and use JavaScript client side to perform the redirection. With JSON like:
{
"redirect": true,
"location": "/content/test-site/sample.html"
}
You could use an AJAX call like this one:
$.ajax({
url: "/bin/test/redirect",
success: function(result){
if(result.redirect){
window.location = result.location;
}
},
error: function(result){
alert("Redirection Failure");
}
});
More on jQuery AJAX.
Answered By - GuillaumeCleme