Darren Wood
Darren Wood

Reputation: 1528

Ajax function failing to hit method on code behind on server

I have the following ajax function

 var jsonId = JSON.stringify(sortedIDs);
 $.ajax({
        type: "POST",
        data: { ids: jsonId },
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        url: "/Intranet/Dev/TestSortTable.aspx/GetData",
        success: function (msg) {
               alert(msg.d + "success");
        },
        error: function (response) {
               alert("an error has occured");
        }
});

And the following method in the code behind page

[WebMethod]
    public static string GetData(string[] data)
    {
        return "this is the string from the code behind file";
    }

The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.

Upvotes: 0

Views: 87

Answers (1)

Barmar
Barmar

Reputation: 780818

You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:

var json = JSON.stringify({data: sortedIDs);
$.ajax({
    type: "POST",
    data: json,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    url: "/Intranet/Dev/TestSortTable.aspx/GetData",
    success: function (msg) {
           alert(msg.d + "success");
    },
    error: function (response) {
           alert("an error has occured");
    }
});

Also, datatype: should be dataType:

Upvotes: 2

Related Questions