Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET: Cannot call Page WebMethod using jQuery

I created a WebMethod in the code-behind file of my page as such:

[System.Web.Services.WebMethod()]
public static string Test()
{
    return "TEST";
}

I created the following HTML page to test it out:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/></script>
    <script type="text/javascript">
        function test() {            
            $.ajax({
                type: "POST",
                url: "http://localhost/TestApp/TestPage.aspx/Test",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function(msg) {
                    alert(msg.d);
                }
            });
        }
    </script>
</head>
<body>
    <button onclick="test();">Click Me</button>
</body>
</html>

When I click the button, the AJAX fires off, but nothing is returned. When I debug my code, the method Test() doesn't even get called. Any ideas?

like image 288
John Avatar asked May 04 '10 20:05

John


2 Answers

try

url: "TestPage.aspx/Test"

or whatever relative url that will hit your page.

You may be inadvertently violating same origin policy.

Also, although you are not there yet, you are expecting a d: wrapped object. As it is you are just going to get a string.

This should get you where you want to go.

    function test() {            
        $.ajax({
            type: "POST",
            url: "TestPage.aspx/Test",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                alert(msg.d);
            }
        });
    }
like image 198
Sky Sanders Avatar answered Sep 29 '22 11:09

Sky Sanders


I think datatype should be "json". Add an error function to see what error status you get back ie 404 not found , 500 server error etc etc

like image 38
James Westgate Avatar answered Sep 29 '22 10:09

James Westgate