How to access page methods from JQuery

Most of the time to make web page ajax, developers were using UpdatePanel with Script Manager and sometimes (most of the time in my experience) the update panel will affect the performance of the Page. One of the project I used script manager and Pagemethods for the ajax implementation. The current project I am working, I got some weired error from Script Manager, the error was Sys.Net was not defined. I tried various solutions to fix this but it was throwing the same exception :( and the funny thing, it was working perfectly in one page. :) So I thought doing the same thing with JQuery, and here is the code snippet, which will help to access page methods using JQuery.

Here is my page method.

public static int Add(int a, int b)
    return a + b;

And here is my javascript code to access PageMethod

var dataToPost = { 'a': '10', 'b': '20' };
    type: "POST",
    url: "chat.aspx/Add",
    data: JSON.stringify(dataToPost),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (res) { alert("Result :" + res.d); },
    error: function (res) {
        alert("An exception occured:" 
    + res.statusText); }

The type parameter defines the type of HTTP operation(GET / POST), url is the location to post/get data, data is the list of the parameters, the page method expects. You don’t need to use stringify method, but I found some problem without using it. The success and error are event handlers, which will fire when request was successful and server is returning some value, or if there is any error.

Happy Programming :)

2 thoughts on “How to access page methods from JQuery

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>