简体   繁体   中英

Executing commands sequentially in Javascript

I'd appreciate any suggestions to get this resolved.

I am using a JS function checkAvailability() to confirm if a group is available for addition to a database. (For some reasons, database key constraints were not applied) While doing this, sometimes my function returns even before receiving the output from the PHP file.

So I get a mixed result. When the output from PHP file is received, it shows the correct result. But rest of the times it just returns false.

Any pointers on how this can be fixed? The code follows:

Thanks, Vish

//function to check groupname availability

function checkAvailability(){
        var grpname = $('#groupname').val();
        var isAvailable = false 

        //use ajax to run the check
        $.post("checkGroupName.php", { gname: grpname },
            function(result){
                if(Number(result) == 0){
                    //show that the groupname is available
                    isAvailable = true ;
                    $('#username_availability_result').html(grpname + ' is Available');
                }
                else{
                    //show that the groupname is NOT available
                    isAvailable = false ;
                    $('#username_availability_result').html(grpname + ' is already taken');

                }
        });

    alert("isAvailable : "+isAvailable);
    return isAvailable ;
}  

checkGroupName.php file

$gname = $_POST['gname'];
$query = "SELECT * FROM groups WHERE group_name='$gname'";
$result = mysql_query($query);
if(mysql_num_rows($result)){        
    echo 1; 
else
    echo 0;

Your function should always be returning before your ajax request to the PHP page completes, because the ajax request is asynchronous . You start it in your function, but it completes after the network operations are done. .post doesn't block waiting for the result.

You can make it block by using .ajax rather than .post with the async: false option, but on many browsers that locks up the UI in an unpleasant way during the network request.

Instead, have your function accept a callback that it will call with the result of the operation:

function checkAvailability(callback) {
    var grpname = $('#groupname').val();

    //use ajax to run the check
    $.post("checkGroupName.php", { gname: grpname },
        function(result){
            if(Number(result) == 0){
                //show that the groupname is available
                $('#username_availability_result').html(grpname + ' is Available');
                callback(true);
            }
            else{
                //show that the groupname is NOT available
                $('#username_availability_result').html(grpname + ' is already taken');
                callback(false);
            }
    });
}  

Code that used to do this:

doSomething();
if (checkAvailability()) {
    itsAvailableLetsDoSomething();
    moreAvailableStuff();
}
else {
    itsNotAvailableDoSomethingElse();
    otherStuff();
}

...would instead look like this:

doSomething();
checkAvailability(function(available) {
    if (available) {
        itsAvailableLetsDoSomething();
        moreAvailableStuff();
    }
    else {
        itsNotAvailableDoSomethingElse();
        otherStuff();
    }
});

As you can see, the impact is minimal, but by doing this you're taking advantage of asynchronous communication to keep your UI responsive.

the problem is that $.post sends the request asynchronously and so the rest of the code is executed before the response arrives from the server.

the solution is to use $.ajax() and to set async option to false so that the call is synchronous. something like:

function checkAvailability(){
        var grpname = $('#groupname').val();
        var isAvailable = false 

        //use ajax to run the check
        $.ajax({
                type: 'post',
                url: 'checkGroupName.php',
                dataType: 'json',
                data:  { gname: grpname },
                async: false, 
                success: function(result){
                  if(Number(result) == 0){
                    //show that the groupname is available
                    isAvailable = true ;
                    $('#username_availability_result').html(grpname + ' is Available');
                }
                else{
                    //show that the groupname is NOT available
                    isAvailable = false ;
                    $('#username_availability_result').html(grpname + ' is already taken');

                }
        });

    alert("isAvailable : "+isAvailable);
    return isAvailable ;
}  

You can try this code

function checkAvailability(){

 var grpname = $('#groupname').val();
    var isAvailable = false 
    $.ajax({
        type: "POST",
        url: "checkGroupName.php",
        data: {grpname : grpname },
        success: function (result) { 
        if(Number(result) == 0){
                //show that the groupname is available
                isAvailable = true ;
                $('#username_availability_result').html(grpname + ' is Available');
            }
            else{
                //show that the groupname is NOT available
                isAvailable = false ;
                $('#username_availability_result').html(grpname + ' is already taken');

            }}
    });

}

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