I'm trying to call a simple static WebMethod in my ASP.NET Webforms page using jQuery Ajax, but it doesn't seem to be working. I've tried enabling anonymous authentication and other fixes suggested online, but nothing helps.
Here's my code:
<script>
$(document).ready(function () {
$("#btnCall").click(function () {
var name = $("#txtName").val();
$.ajax({
type: "POST",
url: "AjaxTest.aspx/SayHello",
data: JSON.stringify({ name: name }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#result").text(response.d);
},
error: function (xhr, status, error) {
console.error(error);
$("#result").text("Error: " + error);
}
});
});
});
</script>
Code-behind (AjaxTest.aspx.cs):
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string SayHello(string name)
{
return "Hello " + name;
}
I just want to click a button, send a value to the backend, and show the returned text (Hello [name]) on the page. However, the Ajax call fails and the browser console shows an error (or nothing happens).
What I've tried:
- Enabled anonymous authentication in IIS
- Added
[System.Web.Services.WebMethod]explicitly - Made sure the method is
public static - Verified the URL and case sensitivity
- Checked network tab (sometimes shows 500 "Internal Server Error")
