crmepham
crmepham

Reputation: 4750

unable to compare returned String from AJAX call

I am using AJAX to check a user's login details are correct. Currently if the details are correct I output "success" which is returned to the AJAX call and should be alerted. When I attempt to compare the returned String it is always falls when I try == and ===.

Here is the AJAX:

$("#loginForm").submit(function(e){
    e.preventDefault(); //STOP default action
    var postData    = $("#loginForm").serializeArray();
    var username    = $("#username").val();
    var password    = $("#password").val();

    if(username.length > 0 && password.length >){
        $.ajax(
            {
                type: "POST",
                url : "HomeController",
                data : postData,
                success: function(data) 
                {

                    if(data == "success"){
                        alert(data);
                    }


                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#loginResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
                }
            });
    }else{
        $("#loginResult").html("<p>Unable to login: ensure details are correct.</p>");
    }
});

and the HomeController returning "success":

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String form         = request.getParameter("form");

    // check login details
    if(form.equals("loginForm")){
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();

        PrintWriter out = response.getWriter(); 

        password = loginService.hashPassword(password);
        boolean isValidUser = loginService.checkUser(username, password);

        if(isValidUser){

            // set session
            HttpSession session = request.getSession();
            session.setAttribute("loggedIn", "true");

            out.println("success");

        }else{
            out.println("Incorrect login details.");
        }
    }
}

I know that it is returning "success" because when I remove the if statement it alerts "success".

Why will it not successfully compare the two Strings?

Upvotes: 0

Views: 474

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97247

Use out.print("success") instead of out.println("success") in your controller, or trim the newline from your Javascript data object.

Upvotes: 4

Related Questions