0

I'm trying to test a function that is on the server side by calling it from the client side using AJAX.

I get this error every time I invoke the AJAX method:

http://localhost:5958/myaccount/notifications/myaccount/notifications/Default.aspx/method Failed to load resource: the server responded with a status of 404 (Not Found)

Here's my AJAX function:

    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "myaccount/notifications/Default.aspx/method",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }

HTML control :

<input id="btnGetTime" type="button" value="Show Current Time"
    onclick="ShowCurrentTime()" />

Function I'm trying to call on the server side:

        [WebMethod]
    protected bool method()
    {
        return true;
    }

What's the correct way of doing this?

Update

Changed the url to : '<%= ResolveUrl("~/default.aspx/method") %>' and now I'm getting 500 Internal Server Error.

Update2

The internal error was due to [HttpPost] attribute which I changed to [WebMethod] and it works.

Ahmed Mujtaba
  • 2,110
  • 5
  • 36
  • 67
  • Take a look at the accepted answer to this SO question: http://stackoverflow.com/questions/6928533/calling-a-webmethod-with-jquery-in-asp-net-webforms Try creating the URL for the target WebMethod the way it's done there rather than hardcoding it – Ian Gilroy Oct 28 '15 at 13:55
  • @IanGilroy changed the url to : <%= ResolveUrl("~/myaccount/notifications/Default.aspx/method") %> and now I'm getting this error : Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'notifications' – Ahmed Mujtaba Oct 28 '15 at 14:08
  • maybe you can refer to another link like this: [ajax call jquery asp.net mvc](http://stackoverflow.com/questions/414726/asp-net-mvc-and-jquery-get-info-to-controller) – Jack1987 Oct 28 '15 at 14:44

3 Answers3

1

I think the problem is in your url.

Use a leading slash(/) like following.

url:"/myaccount/notifications/Default.aspx/method"
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
1

Your server side call must be static public. https://msdn.microsoft.com/en-us/library/bb398998(v=vs.90).aspx

[WebMethod]
public static bool method()
{
    return true;
}
g2000
  • 480
  • 3
  • 8
0

I assume you are not passing any parameter. So can you try Data:{} instead of Data:"{}".