I am having trouble making a WebMethod to work. It's all set up properly, and i have simplified it to the smallest example.
AJAX:
function DoAJAX() {
$.ajax({
type: 'POST',
url: 'faq.aspx/DoAJAX',
data: "AJAX Test",
dataType: 'text',
success: function (data, status) {
debugger;
alert(status + " " + data)
},
error: function () {
alert("error!")
}
});
}
WebMethod (in faq.aspx.cs, using System.Web.Services; and public static):
[WebMethod]
public static string DoAJAX(string foo) {
return foo;
}
}
HTML (faq.aspx, with ScriptManager and EnablePageMethods)
<%@ Page Title="" Language="C#" MasterPageFile="~/MP.Master" AutoEventWireup="true" CodeBehind="faq.aspx.cs" Inherits="Lottery.faq" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<input type="button" value="AJAX" onclick="DoAJAX()" />
</asp:Content>
When clicked, the AJAX call returns a success with the following contents in data: http://pastebin.com/X0Vke0qj
A breakpoint in DoAJAX() WebMethod is never reached.
Why don't it return the "AJAX Test" string that was sent, why the WebMethod isn't hit?
Change type to json, add content type and in data, pass foo parameter as json.
$.ajax({
type: 'POST',
url: 'faq.aspx/DoAJAX',
data: "{ 'foo': 'AJAX Test' }",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data, status) {
alert(status + " " + data.d)
},
error: function (xhr, status, error) {
alert("error!")
}
});