Muhammad Nasir Muhammad Nasir - 3 months ago 32
jQuery Question

Ajax post with ASP.NET Webforms

I want to post data to server with ajax call but i am getting an error.

var userdata = {};
userdata["Name"] = "Saran";
var DTO = { 'userdata': userdata };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},

error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()


I have created a function in Default.aspx.cs and tried to access that function with the above call.

[WebMethod]
public static string update(string userdata)
{
return "Posted";
}


Error :


POST http://localhost:33762/Default.aspx/update 401 Unauthorized 52ms


Message "Authentication failed." StackTrace null ExceptionType

"System.InvalidOperationException"

Answer

Firstly, you have to set/update to settings.AutoRedirectMode = RedirectMode.Off; in App_Start/RouteConfig.cs.

Secondly, your ajax payload is not structured properly to make the appropriate call to the update method. See updates below:

var DTO = { 'userdata': 'Saran' };
$.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         url: "Default.aspx/update",
         data: JSON.stringify(DTO),
         datatype: "json",
         success: function (result) {
           //do something
           alert("SUCCESS = " + result.d);
               console.log(result);
          },
         error: function (xmlhttprequest, textstatus, errorthrown) {
             alert(" conection to the server failed ");
             console.log("error: " + errorthrown);
         }
      });//end of $.ajax()
Comments