1

I have the code to prevent postback but failed. Basically I have an asp.net button.

<asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
        CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />

And ajax call web service.

function ValidateUserName() {
        $.ajax({ type: "POST",
            url: "../UserNameWebService.asmx/ValidateUserName",
            data: "{'strUsername': '" +JSON.stringify( $("#<%=TextUserName.ClientID%>").val()) + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            async: false,
            success: function (data) {
                return data.d;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }


    function ValidateUserNameBeforeSubmitting() {
        var isValid = ValidateUserName();
        return isValid;
    }

The web service will return a boolean value and it does when I step into the code. However when I stepped into the javascript code, I found that "isValid" is not a boolean value. It is "undefined". Why?

Thanks.

  • Try adding alert in success function and check if bool value is returned. – Ravi Vanapalli May 02 '12 at 12:53
  • It has probably something to do with your code-behind. The return value of `UserNameWebService.asmx/ValidateUserName` may not be what you want it to be. Can you post what this function is doing? – DangerMonkey May 02 '12 at 12:55

3 Answers3

1

Ajax is asynchronous.

var isValid = ValidateUserName();

this line executes, but function you're calling has no return (hence undefined)

if you want to access a variable returned from ajax, it needs to be in the success handler.

function ValidateUserName() {
    var returnValue;
    $.ajax({ type: "POST",
        ...
        async: false,
        success: function (data) {
            returnValue = data.d;
        },
        ...
    });
    return returnValue;
}
jbabey
  • 45,965
  • 12
  • 71
  • 94
0

isValid is undefined because ValidateUserName() doesn't actually return anything.

Change the ajax call to this

 function ValidateUserName() {

        var results = $.ajax({ type: "POST",
        url: "../UserNameWebService.asmx/ValidateUserName",
        data: "{'strUsername': '" +JSON.stringify( $("#<%=TextUserName.ClientID%>").val()) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        async: false
    });

    return results;
    //or results.d; if thats what you need for the boolean
}

When the ajax is marked as async:false the result of the ajax call contains your result. Rather than it being passed to a success function

Chris
  • 3,114
  • 1
  • 18
  • 27
  • It depends on the way his code-behind function works, if the return value is in JSON, it need a `success:` function in order to parse the right value. – DangerMonkey May 02 '12 at 12:58
  • @DangerMonkey So how would you parse a JSON value back from a synchronous call? I only noticed that it being syncrounous it should return a value rather than run a success function. – Chris May 02 '12 at 13:00
  • @DangerMonkey aha answered my own [question](http://stackoverflow.com/questions/933713/is-there-a-version-of-getjson-that-doesnt-use-a-call-back) – Chris May 02 '12 at 13:06
0

Scope a return variable so all paths return and make sure your ajax call return a bool:

function ValidateUserName() {
    var result = false; //default 
    $.ajax({ type: "POST",
        url: "../UserNameWebService.asmx/ValidateUserName",
        data: "{'strUsername': '" +JSON.stringify( $("#  <%=TextUserName.ClientID%>").val()) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data) {
            result = data.d;  //make sure this is a bool
            //result = Boolean(data.d); //use this if returning a string, not recommended though
            alert(result); //are you a bool?
        },
        error: function (xhr, ajaxOptions, thrownError) {              
            alert(xhr.status);
            alert(thrownError);
        }
    });

    return result;
}


function ValidateUserNameBeforeSubmitting() {
    var isValid = ValidateUserName();
    return isValid;
}
rick schott
  • 21,012
  • 5
  • 52
  • 81