1

I have a .net project in the framework 4.5.1

When I use ajax like below, it works and the debugger hits the page_load event:

$.ajax({
        "async": true,
        "crossDomain": true,
        type: "POST",
        url: "Advanced.aspx",
        contentType: "application/json; charset=utf-8",
        success: function (ms) {
            alert('success');
        }
    })

In my advanced.aspx.cs, I have the method below:

[System.Web.Services.WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public static string SaveChange(string myval)
        {
            //dummy code for test purposes.
            string u = myval + "X";
            return u;
        }

I want to hit this method via ajax. To do this, I am updating my ajax call like below:

$.ajax({
            "async": true,
            "crossDomain": true,
            type: "POST",
            url: "Advanced.aspx/SaveChange",
            data: {username:"test"},
            contentType: "application/json; charset=utf-8",
            success: function (ms) {
                alert('success');
            }
        })

However, it gives me 401:unauthorized error when i do it in that way, shown below:

enter image description here

How can I fix this? Tried lots of things for the last few hours, no luck.. Any help would be appreciated.

EDIT: I've used async and crossDomain hoping to fix this issue, didn't help. Normally they don't exist in my ajax call, nothing changes.

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82

2 Answers2

1

Found the answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

I have used settings.AutoRedirectMode = RedirectMode.Off; instead of RedirectMode.Permanent in ~/App_Start/RouteConfig.cs, which fixed the issue.

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82
0

Try updating your AJAX JS to:

$.ajax({
    type: "POST",
    url: "Advanced.aspx/SaveChange",
    data: {myval:"test"},
    success: function (ms) {
        alert('success');
    }
})
combatc2
  • 1,215
  • 10
  • 10