Calling Server Side Method Using jQuery/Ajax

With this post I would show how to call server side method from client side. Here we will use jQuery to utilize the Ajax Capabilities which will help us to get/post data to/from server Asynchronously. There are many methods available to perform an async callback to the server. Here I will show a simple example as in how to call a code behind Webmethod.

For simplicity I would be calling the code behind method on a Button Click. Here is the code:

Aspx markup:

   1: <asp:Button ID="Button1" runat="server" Text="Click" />
   2: <br /><br />
   3: <div id="myDiv"></div>

jQuery:

   1: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
   2:   <script type ="text/javascript">
   3:       $(document).ready(function () {
   4:           $('#<%=Button1.ClientID %>').click(function () {
   5:               $.ajax({
   6:                   type: "POST",
   7:                   url: "WebForm1.aspx/ServerSideMethod",
   8:                   data: "{}",
   9:                   contentType: "application/json; charset=utf-8",
  10:                   dataType: "json",
  11:                   async: true,
  12:                   cache: false,
  13:                   success: function (msg) {
  14:                       $('#myDiv').text(msg.d); 
  15:                   }
  16:               })
  17:               return false;
  18:           });
  19:       });
  20:   </script>

Code Behind (C#):

   1: [WebMethod]
   2:    public static string ServerSideMethod()
   3:    {
   4:        return "Message from server.";
   5:    }

In the above code, the aspx markup contains a button on click of which we would call the server side method named ServerSideMethod(). The div would show the message returned from the server. When you run the code above and click the button, it would the div would show the message "Message from server".

If you want to send parameters to your code behind method, you would change the line 8 in the above jQuery code as:

   1: data: "{'param1': 1}"

With the above line I would be sending a parameter with value as 1 to the server side method.

The method would change as:

   1: [WebMethod]
   2:    public static string ServerSideMethod(string param1)
   3:    {
   4:        return "Message from server with parameter:"+param1;
   5:    }

The output will now be:

Message from server with parameter:1

You could also call any webmethod method in your webservice by changing the url in the jQuery as:

   1: url: "WebService1.asmx/ServerSideMethod"

where WebService1 is your webservice and ServerSideMethod is your webmethod in WebService1.

Recently I have seen a lot of questions from members in the asp.net forums asking about how to call Javascript confirm on button click and then based on user selection ie Yes/No process code behind logic.

Here is another example of how to do so:

   1: function MyConfirmMethod() {
   2:         if (confirm('Are your sure?')) {
   3:             $.ajax({
   4:                 type: "POST",
   5:                 url: "WebForm1.aspx/ServerSideMethod",
   6:                 data: "{}",
   7:                 contentType: "application/json; charset=utf-8",
   8:                 dataType: "json",
   9:                 success: function (msg) {
  10:                     $('#myDiv').text(msg.d);
  11:                 }
  12:             });
  13:             return false;
  14:         }
  15:         else {
  16:             return false;
  17:         }
  18:     }
   1: protected void Page_Load(object sender, EventArgs e)
   2:   {
   3:       Button1.Attributes.Add("onclick", "return MyConfirmMethod();");
   4:   }
   5:   [WebMethod]
   6:   public static string ServerSideMethod()
   7:   {
   8:       return "Message from server!";
   9:   }

Above you will see I am calling javascript confirm on the button click. On pressing yes, jQuery calls code behind method ServerSideMethod and returns back the message. You could perform any server side logic/database operations here based on the user response. Note I use return false as it prevents postback to the server.

13 Comments

  • I was just experimenting today with AJAX Page Methods. Instead of returning a simple string I figured out how to return complex data objects like arrays of strings and arrays of objects. I also worked out the JavaScript for referencing the properties of the complex data objects.

  • Good article. Thanks.

    I have a question though: do webmethods go through the page cycle? In other words; will init load and prerender (and others...) execute?

  • Thanks

    Page methods don't have any overhead of the page life cycle. They don't create an instance of the Page, so there is no overhead normally associated with ASPX pages.

  • How did you do it? Can you post your code? Are you able to pass an array of objects to the WebMethods also?

    var objTest = {};
    objTest.FirstName = "John";
    objTest.LastName = "Doe";
    objTest.Age = 25;

    var objArray = new Array();
    objArray[0] = objTest;

    CallWebMethod(objArray,onSuccess,onFail){
    .
    .

    }

    >>I was just experimenting today with AJAX Page Methods. Instead of returning a simple string I figured out how to return complex data objects like arrays of strings and arrays of objects. I also worked out the JavaScript for referencing the properties of the complex data objects.

  • Is the url the path within the project itself with respect to the aspx page or the actual url of the website?

  • @Cor
    As the post above and the example shows how to call the code behind method. So the URL that I have is in respect to your aspx (webpage). So if Page1.aspx is your page then the server side webmethod should be in your Page1.aspx.cs.
    You could also use and specify a Handler.ashx, Webservice.asmx.

  • When would one use a webservice method vs a server side method to service the Ajax request? I mean is there a best practise defined when to use what method?

  • Only works for STATIC methods?

  • Nice yar this is very usful for me...thanks :-)

  • I examined your second example (If you want to send parameters to your code behind method...) It doesn't work properly! :-( I have this problem, too!
    Sending parameter with data:"{'name': value}" doesn't work!

  • Excellent article!!!!!!!!!!!!!111

  • Can i call the same server side function using $get() method? If yes then can you provide a sample?

    Thanks.

  • Check this http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

Comments have been disabled for this content.