JavaScript form validation not awaiting AJAX response

this is part of the check in my form

function check(theform) {
var re = /^\w[0-9A-Za-z]{5,19}$/;
if (!re.test(theform.username.value)) { 
    alert("not valid username");
    theform.username.focus();
    return false;
}

$.ajax({
    type: "POST",
    url: "username.asp",
    data: "username="+theform.username.value,
    success: function(msg){
        username = msg;
        if (!username) {
            alert("username already in use");
            return false;
        }
    }
});

var re = /^\w[0-9A-Za-z]{5,19}$/;
if (!re.test(theform.password.value)) { 
    alert("not valid password");
    theform.password.focus();
    return false;
}
}

for some reason synchronization ... it checks the username and then duplicates the username using ajax and does not wait for a response and proceeds to check the password.

I don’t want to embed the rest of the code in isreadystate (or whatever), because I can move the double validation of the username to the end ... and then the function will end before ajax anyway

what should I do?

+3
source share
2 answers

The first A in AJAX means "Asynchonous." The call is executed, and the function continues, without waiting for the call to return.

async false, . , return false check, jQuery:

Ajax "", , , . async $.ajax() true, , . false (, , ) , , .

, , Ajax .


. , - FF 3.6.

var name_success = true;

$.ajax({
    type: "POST",
    async: false,
    url: "username.asp",  // Needs to return "EXISTS" in this example 
    data: "username="+theform.username.value,
    success: function(msg){
        username = msg;
        if (username == "EXISTS") {  // Changed callback return value - 
                                     // safer this way
            alert("username already in use");
            name_success = false;   // should work because
                                    // we're in check() scope
            return false;
        }
    }
});

alert (name_success);
+6

, , ajax-, ajax- , .

false , , ajax .

success: function(msg){
    username = msg;
    if (!username) {
        alert("username already in use");
        return false;
    }
}

async: false, , ,

0

Source: https://habr.com/ru/post/1746974/


All Articles