Long time WinForm programmer here but new to the web programming scene. I have Visual Studio 2010 and I created a new WebSite project. I can't seem to get ajax to call a webmethod I created. When I click my button on the page nothing happens at all.
It looks like jquery 1.4.1 gets automatically added in a Scripts folder when I create a WebSite project.
In Default.aspx I add 2 script tags:
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="Scripts/Process.js">
I put a button on the page in where the onclick function is defined in Process.js:
<input id="btnTest" type="button" value="Test" onclick="btnTest_onclick()" />
In Process.js I have the following code:
function btnTest_onclick() {
var strData = JSON.stringify({
userid: 5
});
alert(strData);
$.ajax({
url: 'Default.aspx/GetData',
type: "POST",
data: strData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
failure: Failure,
async: true
});
}
function Success(data) {
alert("success");
}
function Failure(data) {
alert("failure");
}
In Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static string GetData(int id)
{
return "hello, my id is " + id;
}
}
Update-Package jqueryin console to get the latest stable version jquery (or use the UI to do the same, or even do it manually by replacing the script file)errorand notfailure. Replace that.