简体   繁体   中英

Ajax response doesn't equal what I think it should

I'm trying to call a displayUsers function, if response equals " loggedIn " (response is coming from echo statement in php for ajax request). It always jumps straight to the else statement and doesn't execute displayUsers() . However, when I alert response it displays loggedIn.

Here is my code:

   function ajaxRequest(url, method, data, asynch, responseHandler) {
    var request = new XMLHttpRequest();
    request.open(method, url, asynch);

    if (method == "POST") {
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                responseHandler(request.responseText);
            }
        }
    }

    request.send(data);
}

//loginCheck
    function loginCheck() {
        var username = document.getElementById("usernameLogin").value;
        var password = document.getElementById("passwordLogin").value;
        var data="usernameLoginAttempt="+username+"&passwordLoginAttempt="+password;
        ajaxRequest("../PHP/CODE/login_check.php", "POST", data, true, loginCheckResponse);
    }

    function loginCheckResponse(response) {
    //check response, if it is "loggedIn" then call show users function
    alert(response);
    if (response == "loggedIn") {
        displayUsers();
    } else {
        alert("Login Failed. Please try again.")

    }

}
// response is an object which you get from ajex.
// You have not written how you call loginCheckResponse()
// call like loginCheckResponse(response.<variable which you return from service page>)
function loginCheckResponse(response)
{
    //check response, if it is "loggedIn" then call show users function
    alert(response);
    if (response == "loggedIn") {
        displayUsers();
    } else {
        alert("Login Failed. Please try again.")
    }

}

Changed my code to:

    //logged in
function loginCheckResponse(response) {

    if(response.trim()=="loggedIn"){
        displayUsers();
    }
    else{
        alert("Login Failed. Please try again.");
    }

}

It now works. Thanks for the help anyway people.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM