John R
John R

Reputation: 2791

Unable to call web method using AJAX post Jquery method

Unable to call UpdateIt method that presents in the Default.aspx.cs by using jQuery Ajax post method.

In Default.aspx:

function ActionComplete(args) {

    var ganttRecord = args.data; if (args.requestType === 'save') {

        $.ajax({
            type: "POST",
            url: "Default.aspx/UpdateIt", 
            data: ganttRecord,
            dataType: "json",
            success: OnSuccess,
            failure: function () {
                alert("Fail");
            }
        });
    }
} function OnSuccess() {
    alert("Pass");
}

In Default.aspx.cs:

[WebMethod]
public static void UpdateIt(TaskData record)
{
    Default sample1 = new Default();
    sample1.Update(record);

}

Kindly help me...

Upvotes: 0

Views: 2002

Answers (2)

Arindam Nayak
Arindam Nayak

Reputation: 7462

Finally i get it working.

Following is the code behind or server side code.

[WebMethod]
public static string UpdateIt(TaskData record)
{
    Update(record);
    return "done";
}
public static void Update(TaskData r)
{
   // Write code to handle whatever you need.
}

NOTE: Update method has to be static as it needs to be called from static method. Also you don't need to create a instance of page class such as Default and then invoke Update method like this - sample1.Update(record);. Because you can definitely call Update directly, as it resides in Default.aspx.cs. That is why, i have used Update(record) inside UpdateIt(TaskData record).

Assumption TaskData has following structure.

public class TaskData
{
    public int id { get; set; }
    public string name { get; set; }
}

Next, look carefully at JS code.

var tskmgr = { 'record': {"id":"2" , "name": "ajax is happy"} };
$.ajax({
    type: "POST",
    url: "Default.aspx/UpdateIt",
    data: JSON.stringify(tskmgr),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        // alert(data.d);// this will show alert as "done". Check serverside code for more detail
        console.log(data);
    },
    failure: function (a,b,c) {
        alert("Fail");
    }
});

Take a look at JS structure, record is parameter name, i have used that first, then parameter value is object so , i have used object with required properties, then i have used JSON.stringify to send them to server side.

Hope this will work for you.

Upvotes: 1

Manish Goswami
Manish Goswami

Reputation: 875

What is this ?? data: ganttRecord

It should be like this,

      data: '{"param" ,"value"}',

    ADD THIS
      JSON.stringify({'ganttRecord'})


     contentType: "application/json; charset=utf-8",

Change

      public static void       

TO

      public static string  

Upvotes: 1

Related Questions