Click here to Skip to main content
Click here to Skip to main content

Calling ASP.Net WebMethods using jQuery

, 21 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Hey there worldIts a Friday afternoon and you want to do some hot and funky code using WebMethods and AJAX but you then encounter the problems and excess baggage of Microsoft's Ajax Implementation. Why not use jQuery? Well with this neat code snippet below, you can now call a WebMethod in a ASP.Net
Hey there world

Its a Friday afternoon and you want to do some hot and funky code using WebMethods and AJAX but you then encounter the problems and excess baggage of Microsoft's Ajax Implementation. Why not use jQuery? Well with this neat code snippet below, you can now call a WebMethod in a ASP.Net page without all the baggage of ASP.Net AJAX Client Script libraries! All you need is ASP.Net, JQuery and a little JSON magic supplied by the jQuery-JSON library plugin http://code.google.com/p/jquery-json/

(function ($) {
    $.webMethod = function (options) {
        var settings = $.extend({
            'methodName': '',
            'async': false,
            'cache': false,
            timeout: 30000,
            debug: false,
            'parameters': {},
            success: function (response) { },
            error: function (response) { }
        }, options);         var parameterjson = "{}";
        var result = null;
        if (settings.parameters != null) { parameterjson = $.toJSON(settings.parameters); }
        $.ajax({
            type: "POST",
            url: location.pathname + "/" + settings.methodName,
            data: parameterjson,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: settings.async,
            cache: settings.cache,
            timeout: settings.timeout,
            success: function (value) {
                result = value.d;
                settings.success(result);
            },
            error: function (response) {
                settings.error(response);
                if (settings.debug) { alert("Error Calling Method \"" + settings.methodName + "\"\n\n+" + response.responseText); }
            }
        });
        return result;
    };
})(jQuery);
Simply pasting this code into a Javascript file and referencing it after your favourite version of the jQuery Library creates a new jQuery method called "webMethod".

The following parameters are available:

methodName

Denotes the name of the Server-side method to call

async

Determine if jQuery is to wait for the Server side process to finish.

cache

Determine if jQuery will append caching headers to the request.

timeout

Timeout to wait for a server response

debug

When set to true, a Javascript alert box is shown if any runtime error occurs on the server.

parameters

A Object containing any parameters to pass to the server-side method.

success

A Callback function which is run when the request completes successfully. The results from the server side function are passed as a parameter.

error

A Callback function which runs when the request fails in some way. The standard Error object is passed as a parameter.

This snippet below calls the GetDate() WebMethod shown

$.webMethod({ 'methodName': 'GetDate', 'parameters': { 'client': 3 },
                success: function (value) { alert(value); }
            });
And the C# Codebehind thats being called by this function:
[WebMethod]
        public static string GetDate(int client)
        {
            return string.Format("{0} says {1}", client, DateTime.Now.ToString("r"));
        }
Note the all-important [WebMethod] Declaration that tells ASP.Net to work its Server-Side ASP.Net AJAX Magic..

Simples! And all in a few lines of code - A much smaller footprint.

Thanks to the jQuery-JSON Plugin here http://code.google.com/p/jquery-json/ for the excellent JSON Conversion routines.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

JCrocker
Software Developer (Senior)
United Kingdom United Kingdom
Senior Developer with over 10 years experience of Microsoft Technologies working on both Web and WinForms Client Applications.
 
Keeper of 3 Chickens and enjoys Archery.
Follow on   Twitter

Comments and Discussions

 
QuestionWhat about async web method calls from jQuery? Pinmemberjportelas31-Jan-13 4:05 
Hi JCrocker,
 
I have a question, is there a way to call async web methods from jQuery. I mean, if you have a GetData() method exposed in your web service, you can also have BeginGetData() and EndGetData() if you allow WCF to create async methods. Is there a way to call the BeginGetData() method and switch somehow to the EndGetData() as it is done on server side code?
 
Thanks!
jportelas

QuestionMy Vote Of 2 PinmemberAlireza_136221-Jan-13 23:17 
QuestionPassing a list of values PinmemberMember 248752224-Sep-12 5:51 
GeneralMy vote of 1 Pinmembermahmoud elghandour22-May-12 2:49 
GeneralMy vote of 1 Pinmembermhamad zarif29-Nov-11 9:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 21 Nov 2011
Article Copyright 2011 by JCrocker
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid