简体   繁体   中英

UPDATED form validation error in javascript

from the coding below, if some data are wrong, it will alert false. it works fine if the confirmed pw is not same as the password. however, if the loginID checking seems gotta some problems. it alert true789 false false123 false456 respectively. why the consequence is not false123 false456 false789 false? because of the delay from json? how to solve it?

var result = "true";

$('#test').click(function(){
    validation();
    alert(result);  
});

function validation(){  
    result = "true";
    var loginID = $("#loginID").val();
    var role = $("#role").text();

    // check Login Name
    if (loginID == "" || loginID == null){
        $('#errorID').empty();
        $('#errorID').append(
            '<h6>' + "The Login Name cannot be empty" + '</h6>'
        );
        $("#errorID").show();
        result="false";
    } else {
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            jsonpCallback: "jsoncallback",
            data: {
                ID: loginID,
                role: role          
            },
            url: "http://mydomain.com/checkID.php?jsoncallback=?",

            success: function(data){
                if (data[0].data.user_name!=""){    
                    result="false";
                    alert(result+"123");
                    $('#errorID').empty();
                    $('#errorID').append(
                        '<h6>' + "The Login Name " + data[0].data.user_name + 
                        " is used." + '</h6>'
                    );
                    $("#errorID").show();
                    alert(result+"456");
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert("Request failed: " + textStatus + errorThrown);
                result="false";
            }
        }); //end of ajax
    }
    alert(result+"789");            
    return result;
} // end of #validation

the ajax call is done asynchronous. it enters the ajax() function then carries on and when the result will eventually come the alerts or whatever you have in the event handlers will trigger. You can add a async : false to your ajax call that will change how things run. The 789 alert will only run after the ajax call is done and responded. Also, if your ajax call is made to your domain then you don't need the jsonpCallback and if the headers of the response are application/json then you should remove dataType as well and leave it to jQuery to handle it correctly

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