0

I have AJAX using jQuery which gets triggered when I click a link with the ID logOut.

AJAX:

$("#logOut").click(function(){
  $.ajax({ 
    url: "Logout"
  });
});

The AJAX calls my Java Servlet, see below:

/**
 * Servlet implementation class Logout
 */
@WebServlet(description = "Logout User", urlPatterns = { "/Logout" })
public class Logout extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     *//*
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }*/

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.setStatus(response.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", "index.jsp#login");
    }

}

When the link is clicked my jQuery always triggers however it does not always seem to call the logout Java Servlet. Why is this happening?

EDIT:

When I step through the jQuery code using Chrome dev tools it works but not when it's ran normally.

HTML:

<li><a class="linkButtons" href="" id="logOut">Log Out</a></li>

Colin747
  • 4,955
  • 18
  • 70
  • 118

3 Answers3

2

In your HTML code, you need to put the URL mapping of your servlet in the href attribute:

<li><a class="linkButtons" href="Logout" id="logOut">Log Out</a></li>

This way when it's submitted, the request will be sent to the correct URL.

tonga
  • 11,749
  • 25
  • 75
  • 96
0

You probably need to turn off caching:

$.ajax({
    url: "Logout",
    cache: false
});

Update: Try this - prevent the link from being followed on click -- it is probably redirecting the page before the AJAX call can be fired...

$("#logOut").click(function(e){
    e.preventDefault();
    $.ajax({ 
        url: "Logout",
        cache: false
    });
});

This post has good answer addressing preventing defaults: jQuery disable a link

If you must reload the page, then you will still want to disable the link to ensure the Logout action occurs. To redirect after logout, simply add the success handler or .done function to your ajax call to reload the page.

Community
  • 1
  • 1
David Fleeman
  • 2,588
  • 14
  • 17
0

Try following code

   $(document).ready(function() {
        $("a#logOut").click(function() {
            $.get("Logout");
        });
    });
Shamse Alam
  • 1,285
  • 10
  • 21