user1108948
user1108948

Reputation:

ajax call web service: return undefined

I have a jquery ajax call asp.net web service but it is not working. I got an error:

isValid is underfined.

I set a breakpoint and found that the code never reaches web service. Jquery:

<script src="../jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
    function ValidateUserName() {
        var isValid;
        $.ajax({ type: "POST",
            url: "UserNameWebService.asmx/ValidateUserName",
            data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                isValid = data;
            }
        });
         return isValid;
        } 
</script>

web service code:

 [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class UserNameWebService : System.Web.Services.WebService
{

    [WebMethod]
    public bool ValidateUserName(string strUsername)
    {
        \\ then return something by logic

Thank you.

Upvotes: 0

Views: 2798

Answers (1)

Tim B James
Tim B James

Reputation: 20364

You are returning isValid before your Ajax is complete. The best thing to do is write a function which is called on the completion of your Ajax call.

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

Then deal with the returned data here.

function RenderResult(data){
    // handle the returned result here
    var isValid = data;
}

Upvotes: 3

Related Questions