简体   繁体   中英

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"

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM