mercredi 6 mai 2015

JQuery ajax post function is executed at the end of javascript

i have a problem with validating if the username is already taken. I am trying to find out if the username already exists using the "post" method of jquery. But when executing this function, the script is alway jumping to the end of the function and is doing the rest of the script first before executing the "post" command. Could you please review my code and help me?

$("#submit").click(function () {

    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var passwort = document.getElementById("passwort").value;
    var passwort2 = document.getElementById("passwort2").value;
    var validate = false;

    checkUsername();

    if (validate == true) {
        $.post("Login/register.php", {

            username: username,
            email: email,
            passwort: passwort,
            passwort2: passwort2,
        }, function (info) {
            $("#errorBox").empty();
            $("#errorBox").html(info);
        });

    } else {
        $('#register').submit(function () {
            return false;
        });
    }

    function checkUsername() {
        username = document.getElementById("username").value;
        // username = replaceUmlauts(username);
        if (username.length > 0) {
            document.getElementById("username").style.borderColor = "";
            // document.getElementById("errorBox").innerHTML =
            // "";
            validate = true;
            checkAvailability();
            return false;
        } else {
            document.getElementById("username").style.borderColor = "red";
            document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
            // alert('Username must be longer than one sign');
            validate = false;
            return false;
        }
    }

    function checkAvailability() {
        $.post(
            "Login/checkusername.php", {
                username: username
            },
            function (result) {
                // if the result is 1
                if (result == 1) {
                    // show that the username is
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "";
                    return false;
                } else {
                    // show that the username is NOT
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
                    document
                        .getElementById("username").style.borderColor = "red";
                    validate = false;
                    return false;
                }
            });

    }
    return false;

});

Aucun commentaire:

Enregistrer un commentaire