I have a Web Site Project (ASP.NET 3.5).
One of the methods is in Search.aspx.cs looks like this. This is a method I am trying to call so I can return some data to Ajax call:
[WebMethod]
public static string TestMethod(string param)
{
return "It worked";
}
Having difficulty calling the above method from client side button click from inside the Search.aspx page :
<form runat="server" id="mainForm" class="form-horizontal">
<input id="addButton" type="button" value="Add" />
</form>
<script>
$('#addButton').click(function () {
$.ajax({
type: "GET",
url: "Search.aspx/TestMethod",
data: "{}",
contentType: "application/json",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
});
</script>
Here is the screen showing alert box from error ajax function.
Here is another from Firefox debugger:
Here is a screenshot with a complete error from Firefox debugger:
Your method expects to receive a parameter...
change your method to this:
[WebMethod]
public static string TestMethod()
{
return "It worked";
}
Or change your js to this (you have to use POST type):
<script>
$('#addButton').click(function () {
$.ajax({
type: "POST",
url: "Search.aspx/TestMethod",
data: JSON.stringify({ "param" : "anything"}),
contentType: "application/json",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
});
</script>