views:

55

answers:

2

Hi,

I want to call a webservice using jQuery.ajax() but the webervice doesn't get called. - If I change the url: to reference a .ashx file it gets called but not .asmx?

Here's the code I'm using:

jQuery.ajax({
        type: "POST",
        url: "/services/CheckUsername.asmx/CheckUsername", // this doesn't get called
        //url: "/services/CheckUsername.ashx/ProcessRequest", this gets called
        data: '{ "context": "' + "username" + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',

        success: function (msg) {
            alert("Result: " + msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Error: " + textStatus)
        }

The .ashx file gets called but a parsererror is retuned because it's returning http context - how can I modify this to get a string return type from a webservice?

Thanks,

+2  A: 

try setting [ScriptMethod] attribute to your server side method

Elangovan
Thanks for your reply, Elangovan. I'm not sure where to put [ScriptMethod] - do you mean add it to the webservice c# code above the method? i.e like [WebMethod] is above the method name.
aspdotnetuser
I used the following thread as a reference: http://stackoverflow.com/questions/1791088/asp-net-scriptmethod-generating-empty-json and added [ScriptMethod(ResponseFormat = ResponseFormat.Json)] but VS doesn't recognise it as correct syntax?
aspdotnetuser
It should be added like [ScriptMethod]syntax is correct, but refer the name space System.Web.Script.Services in your asmx file.
Elangovan
@aspdotnetuser - Is this C# or VB? The syntax is different.
Nick Craver
+1  A: 

I found out how to pass the username entered by the user to the HTTP handler. Here's the jQuery code:

jQuery.validator.addMethod("UsernameCheck", function (value, element) {
        var allowed = true;
        jQuery.ajax({
            url: "/services/UsernameCheck.ashx",
            global: false,
            cache: false,
            type: "get",
            data: "profile_name=" + jQuery("#username").val(),
            dataType: "text",
            success: function (msg) {
                if (msg == 1) {
                    allowed = true;
                }
                else {
                    allowed = false;
                }
            }
        });
        return allowed;
    }, "Please enter a valid username");
aspdotnetuser