0

I have a login jsp, and a servlet that processes the login. The servlet is called by jquery ajax. If the email or password is incorrect, a message from the servlet will be displayed in a div.

response.getWriter().write("Incorrect");

But if it is correct, the servlet calls:

response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print("{\"redirect:\",\"homepage.jsp\"}");

I followed the steps here How to manage a redirect request after a jQuery Ajax call to manage response.sendRedirect calls by the servlet. I got it to display the message if the email/password is incorrect, but it's not redirecting, homepage.jsp got included in the login page. Here's the ajax.

$( "#login" ).submit(function( event ) {
event.preventDefault();
$.post(
$(this).attr( "action" ),
{ email: $(this).find( "input[name='email']" ).val(),
password: $(this).find( "input[name='password']" ).val()})
.done(function( data, textStatus) {
if (data.redirect) {
window.location.href = data.redirect;
} else {
$( "#message" ).empty().append( data ); // display to a div
}
},"json");
});

What should I do?

Community
  • 1
  • 1
lightning_missile
  • 2,821
  • 5
  • 30
  • 58
  • http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call – Jiang YD Sep 08 '15 at 06:52
  • btw, ajax is for live data, not for url jumping. – Jiang YD Sep 08 '15 at 06:53
  • @Jiang YD I referenced that link in my question – lightning_missile Sep 08 '15 at 06:59
  • yes, but did you notice that `This works only if you have control on server`? for this client side codes, you need send a json `{redirect:"homepage.jsp"}`, rather than use `response.sendRedirect`. – Jiang YD Sep 08 '15 at 07:02
  • You forgot to show in your question how you wrote `data.redirect` to the response. It sounds like that you're still sending a redirect instead of returning a JSON string as instructed by the answer you found. – BalusC Sep 08 '15 at 07:04
  • @BalusC I actually didn't create any JSON object. Now I have one: response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print("{\"redirect:\",\"homepage.jsp\"}");, still not working. – lightning_missile Sep 08 '15 at 07:57
  • It would be helpful if you elaborate "not working" as web developer, not as enduser. To start, press F12 in browser for clues. – BalusC Sep 08 '15 at 07:58

0 Answers0