Search code examples
c#asp.netjquerywebmethod

Having some trouble making a simple ajax call


I started switching things over to [WebMethod]s but started having trouble and decided I needed to do some more research on how to use them properly.

I put the following in $(document).ready()

                $.ajax({
                type: "POST",
                data: "{}",
                url: "http://localhost:3859/Default.aspx/ajxTest",
                dataType: "json",
                success: function (msg, status) {
                    alert(msg.name + " " + msg.value);
                },
                error: function (xhr, status, error) {
                    var somethingDarkside; //only to put a breakpoint in.
                    alert(xhr.statusText);

                }
            });

My [WebMethod]

    [WebMethod]
    public static string ajxTest()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        DummyString dum = new DummyString("Please","Work");
        string jsonString = ser.Serialize(dum);
        return jsonString;
    }

I never get "Please work". I get "undefined undefined" I'm able to debug in VS and the call enters the [WebMethod], the return string looks correct for JSON but I haven't been able to get a successful call out of it yet. I've got parse errors, transport errors. Everything is inconsistent but nothing has ever been right. I've had up to 47 different blogs, SO posts and google group tabs up today, I can't quite crack it.

The xhr.statusText status is OK as posted. I am getting a status parse error. I'm lost.

Thanks in advance.

EDIT: jQuery 1.9.1

EDIT2: DummyString object

        public class DummyString
    {
        public string name { get; set; }
        public string value { get; set; }

        public DummyString(string n, string v)
        {
            name = n;
            value = v;
        }
    }

EDIT 3: Also I have <asp:ScriptManager EnablePageMethods="true" ...


Solution

  • Simplify to:

    $.ajax({
        type: "POST",
        url: "Default.aspx/ajxTest",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert('success');
        },
        error: function (data) {
            alert('fail');
        }
    });
    

    and

    [WebMethod]
    public static string ajxTest()
    {
        return @"{ ""hello"":""hola"" }";
    }
    

    and test. (the above will work)