28

I've set a breakpoint in the following WebMethod but I'm never hitting the breakpoint.

cs:

[WebMethod]
public static string search()
{
    return "worked";
}

aspx:

  function search() {
    $.ajax({
        type: "POST",
        url: "ProcessAudit/req_brws.aspx/search",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg)
        }
    });
}
<button id = "btnSearch" onclick = "search()" >Search</button>
DavidRR
  • 18,291
  • 25
  • 109
  • 191
marknery
  • 1,533
  • 3
  • 19
  • 27

5 Answers5

36

Make sure that you have enabled page methods in your ScriptManager element:

<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />

and that you have canceled the default action of the button by returning false inside the onclick handler, otherwise the page performs a full postback and your AJAX call might never have the time to finish. Here's a full working example:

<%@ Page Language="C#" %>
<script type="text/c#" runat="server">
[System.Web.Services.WebMethod]
public static string search()
{
    return "worked";
}
</script>

<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
        <button id="btnSearch" onclick="search(); return false;" >Search</button>
    </form>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script type="text/javascript">
        function search() {
            $.ajax({
                type: 'POST',
                url: '<%= ResolveUrl("~/default.aspx/search") %>',
                data: '{ }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (msg) {
                    alert(msg.d)
                }
            });
        }
    </script>
</body>
</html>

Another possibility is to subscribe to the click handler unobtrusively:

<button id="btnSearch">Search</button>

and then inside a separate javascript file:

$('#btnSearch').click(function() {
    $.ajax({
        type: 'POST',
        url: '<%= ResolveUrl("~/default.aspx/search") %>',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert(msg.d)
        }
    });
    return false;
});

You might also notice the usage of the msg.d property inside the success callback which ASP.NET uses to wrap the entire response into as well as the usage of the ResolveUrl method to properly generate the url to the page method instead of hardcoding it.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 7
    hmmm... darins slightly wrong... no need to use scriptmanager at all. also charset is unnecessary and so is datatype:json :) – naveen Aug 03 '11 at 15:29
  • Thanks the url was wrong, using '<%=ResolveUrl("~/default.aspx/search") %>' – marknery Aug 03 '11 at 15:37
  • I set up the same way but my response is undefined. Any idea why? I get the following error in my console: `Failed to load resource: the server responded with a status of 500 (Internal Server Error)` – Si8 Jan 19 '17 at 16:44
7

A more optimised call will be

function search() {
    $.ajax({
        type: "POST",
        url: '<%= ResolveUrl("~/ProcessAudit/req_brws.aspx/search") %>',
        data: "{}",
        contentType: "application/json",
        success: function (msg) {
            msg = msg.hasOwnProperty("d") ? msg.d : msg;
            alert(msg);
        }
    });
}

No need to provide a asp:ScriptManager at all.

Resource: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

naveen
  • 53,448
  • 46
  • 161
  • 251
  • 3
    Chrome seems to not like this link because of suspected malware, but I don't want to remove it since I didn't post this. https://www.virustotal.com/en/url/ba8f2c409307ec010ef80629f518aabb85e846e88881a113ba7c2d4259d62cfe/analysis/1485793115/ – KSib Jan 30 '17 at 16:20
4

Your current button is causing a full postback. Simply add a type="button" to your button to avoid this.

 <button id = "btnSearch" type="button" onclick = "search()" >Search</button>

-Shazzam yo

0

How to implement ASP.Net web method using JQuery AJAX ?

HTML Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <title></title>
    <script src="js/jquery.min.js"></script>
    <script>
        function SubmitData() {

            var name = 'Ram';
            var gender = 'Male';
            var age = '30';           

            $.ajax({
                type: "POST",
                url: "ajaxcall.aspx/SaveData",
                data: '{"name":"' + name + '", "gender":"' + gender + '", "age":"' + age + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                    $('#loader').show();
                },
                success: function (data) {

                    alert(data.d);
                    $('#loader').hide();
                },
                error: function (msg) {
                    //alert('3');
                    msg = "There is an error";
                    alert(msg);
                    $('#loader').hide();
                }
            });

        }
    </script>
</head>
<body>
    <div id="loader" style="display: none;">
        <img src="ajax-loader.gif" />
    </div>
    <a href="#" onclick="SubmitData();">Submit</a>
</body>
</html>

Code behind:

[WebMethod]
    public static string SaveData(string name, string gender, string age) {
    try {
        return "OK";
    } catch (Exception ex) {
        return ex.Message;
    } finally { }
}

Resource: http://www.sharepointcafe.net/2016/10/how-to-call-aspnet-web-method-using-jquery-ajax.html

Spikolynn
  • 4,067
  • 2
  • 37
  • 44
user1694660
  • 91
  • 1
  • 1
  • 3
0

In App_Start/RouteConfig.js, comment out this line:

settings.AutoRedirectMode = RedirectMode.Permanent;

Also, make sure you have EnablePageMethods="true" in the asp:ScriptManager opening tag, as Darin Dimitrov said:

<asp:ScriptManager runat="server" EnablePageMethods="true">

Lastly, make sure the webmethod is public static and the parameters that are passed in are of the right datatype. Each of these can be issues that cause the webmethod to not get called.

bryc3monk3y
  • 424
  • 8
  • 12