0

I am trying to make an AJAX call to my servlet but it doesn't work. I can't redirect to a JSP.

This is my AJAX call:

$.ajax({
            url:   '/register',
            type:  'GET'
    });

This is my Servlet:

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    getServletContext().getRequestDispatcher("/prueba.jsp").forward(req, resp);

}

If I use resp.sendRedirect("prueba.jsp"), it does not work, but if I use my browser and put "localhost:8888/register" it works fine!

Please help!

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
JHJ Dev
  • 3
  • 2
  • what you mean by "_it doesn´t work_"? what response do you get? also, it's not clear, are you using `forward()` or `sendRedirect()`? – Igor Artamonov Jun 11 '15 at 10:02
  • There isn´t any response. Both ways are invalid, forward() and sendRedirect(). Thank you. – JHJ Dev Jun 11 '15 at 10:30

1 Answers1

0

You cannot redirect using Ajax. That's the point of Ajax – it's asynchronous, separate from the "main thread".

If you want to simply redirect either:

  • Redirect in the Java code after doing some processing
  • Have a link in the HTML – <a href="/register">Register!</a>
  • If you definitely want to use JavaScript to redirect, have a look at How can I make a redirect page using jQuery?

The last method can be sort-of used with with Ajax. But it's not exactly what you want to do. Have a look at How to redirect using AJAX?

Community
  • 1
  • 1
Crembo
  • 5,198
  • 3
  • 26
  • 30
  • `forward` is not redirect btw, it produces 200 status with content. so it should work, unless there is something wrong in other part (and "isn't any response" probably confirms that) – Igor Artamonov Jun 11 '15 at 11:44
  • @IgorArtamonov you are probably correct, but from what I gathered, JHJ here just wants to redirect. – Crembo Jun 11 '15 at 12:34