Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 921
Muhammad Nasir Avatar asked Dec 25 '22 02:12

Muhammad Nasir


1 Answers

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()
like image 180
Oluwafemi Avatar answered Jan 05 '23 22:01

Oluwafemi