-1

I am checking that if email exist or not using javascript , But it is firing "Email already exist" every time even if email does not already exist. Code is given below :

Javascript code :

 function chkemailExist(source, args) {
        var exists;
        $.ajax({
            type: "POST",
            url: "Register.aspx/DoesUserExist",
            data: "{'emailid': '" + args.Value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (result) {
                exists = result.d;

            }
        });
        args.IsValid = exists;
        if (!exists) {
            var message="Email already exist for" + args.Value + ". ";
            alert(message);
        }
        else { document.getElementById('ContentPlaceHolder1_CustomValidator1').innerHTML = ""; }
    }

Web Method :

   [WebMethod]
   public static bool DoesUserExist(string emailid)

{
    Boolean flg = true;
    //Int32 cntchk = 0;
    PAL_Register reg = new PAL_Register();
    BAL_Register bal_reg = new BAL_Register();
    reg.UserName = emailid;
    flg = bal_reg.checkusername(reg);
    return flg;
}

Please help to get correct my code so it fire alert for exist email only when email already exist in actual.

rahul bhatt
  • 362
  • 1
  • 3
  • 14

2 Answers2

2

AJAX is asynchronous - you're trying to do logic on a variable that doesn't exist yet because the call is in progress. Do your work in the callback!

 function chkemailExist(source, args) {
    var exists;
    $.ajax({
        type: "POST",
        url: "Register.aspx/DoesUserExist",
        data: "{'emailid': '" + args.Value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (result) {
            exists = result.d;
            args.IsValid = exists;
            if (!exists) {
                var message="Although you indicated you're a new customer, an account already exists for " + args.Value + ". ";
                alert(message);
            }
            else { 
                document.getElementById('ContentPlaceHolder1_CustomValidator1').innerHTML = "";
            }
    });
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Comments might be true but I have the feeling that there's another problem anyway : a non-empty string always evaluates to true in javascript, and as the response from your server is not typed (if I'm not mistaken), it will always evaluate to true was the string "true" or "false" ... you should test the string value or return an empty string for false.

cfr this fiddle

Laurent S.
  • 6,816
  • 2
  • 28
  • 40