Search code examples
c#asp.netajaxweb-serviceswebmethod

Posting to WebMethod with ajax error


Step1:

I have defined my script as: on home.aspx page:

function ShowCurrentTime() {
    var post = ({
        method: "POST",
        url: "home.aspx/GetData",
        dataType: 'json',
        data: { name: "Mobile" },
        headers: { "Content-Type": "application/json" },
        success: function (data) {
            alert("here" + data.d.toString());
            alert(data.d);
        },
        failure: function() {
            alert("Fail");
        }
    });
}

Step2:

Call to the script function from button: it's on home.aspx page:

<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />

Step3:

Defined Web method at home.aspx.cs page:

[System.Web.Services.WebMethod]
public static string GetData(string name)
{
    return "Welcome";
}

I am getting:

JavaScript runtime error: Unable to get property 'd' of undefined or null reference


Solution

  • You have to stringify your data:

    data: JSON.stringify({ name: "Mobile" })
    

    And use ajax like this:

    $.ajax({ ... });
    

    Full script updated:

    function ShowCurrentTime() {
        $.ajax({
            method: "POST",
            url: "home.aspx/GetData",
            dataType: 'json',
            data: JSON.stringify({ name: "Mobile" }),
            contentType: "application/json",
            success: function (data) {
                alert("here" + data.d.toString());
                alert(data.d);
            },
            failure: function() {
                alert("Fail");
            }
        });
    }