Search code examples
c#asp.netwebformspagemethods

Ajax request is not working with ASP.NET page method


I tried so many example codes and neither works. Ajax call simply does not return anything. There is no alert popup.

This is the ajax code :

<script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript"> 
    $(document).ready(function() {
        $.ajax({         
            type: "POST",
            url: "mysqlcall.aspx/Testing",
            contentType: "application/json; charset=utf-8",
            data: {""},
            dataType: "json",
            success: function (data) {
                alert("idkbro");
                //  $("#testing").text(response.d);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    });
</script>

And this is the call page :

public partial class mysqlcall : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {    
    }

    public string Testing()
    {
        return "asdlasldalsdl";
    }
}

I'm running it on latest version of IIS and using asp.net C# webforms with routing. mysqlcall.aspx is not routed but it doesn't matter I tried it with a routed page. Any help would be appreciated.

Edit : Thanks to @wazz the problem was in the

url: "mysqlcall.aspx/Testing",

instead it has to begin with a slash like :

url: "/mysqlcall.aspx/Testing",

Solution

  • Add the WebMethod attribute and make the method static:

    [WebMethod]
    public static string Testing()
    {
        return "asdlasldalsdl";
    }
    

    You can also remove data from the ajax call, or remove the quotes.