简体   繁体   中英

Why does this AJAX/Javascript function not work properly until the second time its called?

I have been trying to wrap my head around AJAX requests, and currently implementing some server-side validation for a twitter-bootstrap wizard in Javascript. I am experiencing some bizarre behavior where the function fails the first time its executed, but works as intended the second time. I have simplified my code into this structure:

function do_ajax_validate($user,$email) {
    $.ajax({url: "checkuser.php?field=username&query=" + $user, success: function(result){
        if (result != 'Valid')
            {
                $("#userlabel").html(result);
                $("#userdiv").addClass("has-error");
                $("#userdiv").removeClass("has-success");
                $("#username").focus();
                is_good[0] = false;

            } else {
                $("#userlabel").html($user + " is available!");
                $("#userdiv").removeClass("has-error");
                $("#userdiv").addClass("has-success");
                is_good[0] = true;
                console.log(is_good[0]);

            }
    }});

    console.log(is_good[0]);    

    $.ajax({url: "checkuser.php?field=email&query=" + $email, success: function(result){
        if (result != 'Valid')
            {
                $("#emaillabel").html(result);
                $("#emaildiv").addClass("has-error");
                $("#emaildiv").removeClass("has-success")
                $("#email").focus()
                is_good[1] = false;

            } else {
                $("#emaillabel").html('Looks good!');
                $("#emaildiv").removeClass("has-error");
                $("#emaildiv").addClass("has-success")
                is_good[1] = true;
            }
    }});

    console.log(is_good[0]);
    console.log(is_good[1]);
    if ((is_good[0])&&(is_good[1])) {
        return true;
    }  else {
        return false;
    }
}

Whenever I go into the console and try to run the function, I call it with a user/email that I know is available and get this output:

do_ajax_validate('available_username', 'available@email.address');
false
false
false

Whenever I run the exact same line, I get this output:

do_ajax_validate('available_username', 'available@email.address');
true
true
true

Then checking on a username/email that I know is taken, it returns the last values:

do_ajax_validate('taken_username', 'taken@email.address');
true
true
true

And (you guessed it) - executing the function again returns the expected results:

do_ajax_validate('available_username', 'available@email.address');
false
false
false

I've been trying different methods for hours now and getting these same bizarre results. What am I doing wrong?

Ajax calls run asynchronously in javascript. Your success callback will only be executed once the Ajax call returns, thus your console.log() s can be called before the success functions executes.

You can have a two solutions for this problem:

  1. Work with result inside the callback you assign to success property. Try to console result under the success property
  2. use async: false under AJAX call like:

$.ajax({ url: "checkuser.php?field=username&query=" + $user, async: false, success: function(result){ console.log("result") } });

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