JQuery: Return $.get() callback to outer scope

后端 未结 4 839
生来不讨喜
生来不讨喜 2020-12-22 07:00

I\'m working on this validation script for my latest project, and one of the requirements is that it checks if the value that the user enters is in the database, and if it i

4条回答
  •  生来不讨喜
    2020-12-22 07:24

    The problem is, that your ajax call is asynchron. So your condition check if(hasError) { will be executed before your success handler even set the value for hasError. You can't execute code directly after you initiated your ajax call. Instead have all other code within your success listener.

    if($this.is('.rf_GrpCode') && !hasError)
    {
        $.get("inc/scripts/formHandle.php", { GrpCode: inputValue, type: "groupCode" }, function(data) {
            if(!data.GrpCode)
            {
                errorMsg = "The code you have entered is invalid.";
    
    
                $this.css('background-color','#FFEDEF');
                //alert("Has error: " + errorID);
                if(errorMsg)
                {
    
                    if($('#' + errorID).length)
                    {
                        $('#' + errorID).html(errorMsg);
                    }
                    else
                    {
                        $this.after(errorPrepend + errorMsg + errorAppend);
                    }
                }
            }
            else
            {
                //alert("Has no error: " + errorID);
                $('#' + errorID).remove();
                $this.css('background-color','#FFFFFF');    
            }
        }, "json");
    }
    

提交回复
热议问题