PageMethod call via jQuery

Hi, 

I am trying to call a PageMethod on a SharePoint application page via jQuery. It doesn't seem to touch my method. No errors returned. Am I missing something?, any considerations?. 

Client side:

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

Server side: 

        [System.Web.Services.WebMethod]
        public static void SayHello()
        {
            int i = 0;
        }

November 13th, 2014 11:06am

Did you implement on jQuery call?

 error: function(msg, text) {
                    alert(text);
                }

Add this anotation to your method:

[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

To test, change your method to return a String and them try to access it via Browser, ex.:

http://localhost:1243/TaskDisplay.aspx/SayHello

This way you confirm that requested has been processed and after that try via jQuery again. If you need to call using Get use  type: "GET" instead of  type: "POST" on jQuery call. If you need more information to enable get requests:

http://stackoverflow.com/questions/618900/enable-asp-net-asmx-web-service-for-http-post-get-requests

Free Windows Admin Tool Kit Click here and download it now
November 13th, 2014 1:00pm

Thank you for your response.

It definitely had to do with the format. error: function (msg, text){alert(text)} revealed a "parseerror" message. That along with your suggestion of decorating my method with ResponseFormat = ResponseFormatJson helped me to solve the issue. 

I thought that since I'm working with SP this needed some extra work, glad to see it was only formatting and that I don't have to do a juggling act to call PageMethods on SharePoint application pages. 

Here is the working code: 

$.ajax({
        type: "GET",
        url: "TaskDisplay.aspx/SayHello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            OnSuccess(result);
        },
        failure: function (response) {
            alert(response.d);
        },
error: function(msg, text) {
alert(text);
}
    });

function OnSuccess(result) {
    alert(result);
}

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string SayHello()
{            
     return "Hello";
}


Regards,

Antonio

November 14th, 2014 6:06am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics