How to call PageMethod/Callback/Webservice in ASP.net using JQuery
Callback
function callback(target, params, successFn, errorFn, context, page) {
/// Calls a Callback using Jquery
/// Name of the target your calling, page is __Page
/// Parameters to pass as arguments
/// Function to call when the ajax call finishes
/// Context to return on success
/// Function to call when the ajax call fails
/// (Optional)Page the target belongs to
var forms = $("form").serializeArray();
forms.push({ name: "__CALLBACKID", value: target });
forms.push({ name: "__CALLBACKPARAM", value: params });
page = ((page) ? page : window.location.href.split('#')[0]);
if (page.indexOf(".aspx") == -1) page += "Default.aspx";
$.ajax({
type: "POST",
url: page,
data: $.param(forms),
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
success: ((successFn) ? function(val) { successFn(val.substring(1, val.length), context); } : null),
error: errorFn
});
}
Example:
callback("__Page", "Some argument",
function(msg) {
alert(msg);
});
Page Method & Web Service
Page Method and Web Service has the same exact interface, you query the file that has the method, followed by / and the method name
function pageMethod(fn, params, successFn, errorFn, page, context) {
/// Calls a Page Method using Jquery
/// Name of the Page Method Function you wish to call
/// Object Literal of parameter values that matches the functions paramters
/// Function to call when the ajax call finishes
/// Function to call when the ajax call fails
/// (Optional) Page the method belongs to, by default it goes to the current page from window.location
/// Context to return on success
if (!page) {
page = window.location.href.split('#')[0];
var queries = page.split('?');
page = queries[0] + "/" + fn + ((queries.length > 1) ? "?" + queries[1] : "");
} else { page = page + "/" + fn; }
$.ajax({
type: "POST",
url: page,
data: (params) ? (((typeof params) == "string") ? params : JSON.stringify(params)) : "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ((successFn) ? function(val) { successFn(val.d, context); } : null),
error: errorFn
});
}
You'll notice the function JSON being called, it basically needs to encode any objects into json, the one being used here is from http://www.json.org/js.html
<script src="http://www.json.org/json2.js" type="text/javascript"></script>Example:
pageMethod("GetCats", { Lol: "Cats", Times: 10 },
function(msg) {
alert(msg);
});
Click here to add your own comment!