jQuery AJAX JSON example to call Asp.net server side function or method without any post back

Introduction: In this article I am going to explain with simple example how to call Asp.net C# or VB server side functions or page methods from client side using jQuery AJAX call without reloading/refreshing page.
Call server side functions from jquey json and ajax calls at client side


Description:  By default asp.net web page gets post back when we click on Asp.Net button. For example: Let's consider a very basic example for the sake of simplicity as shown in image above, if we have two textbox controls to enter two numbers and on button click we want to calculate sum of these two numbers. The page will be posted back to server by default to process the request, thus causing slow and annoying page refresh.

But through jQuery AJAX calls we can call the same server side functions i.e. the functions created in the code behind file (.aspx.cs or .aspx.vb) at client side without reloading the page to process the request.

Implementation: Let’s create an example to the concept in action

HTML Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call asp.net server side page methods using jQuery AJAX & json</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>   
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnCalculate").click(function () {
                //Get values from textboxes that will be passed to function
                var num1 = $('#txtFirstNumber').val();
                var num2 = $('#txtSecondNumber').val();
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    //Url is the path of our web method (Page name/function name)
                    url: "MyPage.aspx/CalculateSum",
                    //Pass values to parameters. If function have no parameters, then we need to use data: "{ }",
                    data: "{'Num1':'" + num1 + "', 'Num2':'" + num2 + "'}",
                    //called on ajax call success        
                    success: function (result) {                                      
                        $('#dvMsg').text("Sum of " + num1 + " and " + num2 + " = " + result.d);
                    },
                    //called on ajax call failure
                    error: function (xhr, textStatus, error) {                       
                        $('#dvMsg').text("Error:" + error);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter First Number:</td>
                    <td>
                        <asp:TextBox ID="txtFirstNumber" runat="server" /></td>
                </tr>
                <tr>
                    <td>Enter Second Number:</td>
                    <td>
                        <asp:TextBox ID="txtSecondNumber" runat="server" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Button ID="btnCalculate" Text="Calculate" runat="server" OnClientClick="return false;" />
                        <div id="dvMsg"></div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>

Asp.Net C# Code to call server  side methods using jQuery Ajax calls

In the .aspx.cs file first add following required namespace:

using System.Web.Services;

and then add the following method

       [WebMethod]
        public static string CalculateSum(Int32 Num1, Int32 Num2)
        {          
            Int32 Result = Num1 + Num2;
            return Result.ToString();
        }

Asp.Net VB Code to call server side methods using jQuery Ajax calls

In the .aspx.vb file first add following required namespace:

Imports System.Web.Services

and then add the following method

  <WebMethod> _
    Public Shared Function CalculateSum(Num1 As Int32, Num2 As Int32) As String
        Dim Result As Int32 = Num1 + Num2
        Return Result.ToString()
    End Function

Now over to you:
" I hope you have got how to Call Asp.net Server side Function or Method using jQuery JSON and Ajax calls without any post back and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 
Previous
Next Post »

2 comments

Click here for comments
Unknown
admin
July 26, 2015 ×

I'm getting an error here. Unkown web method [myWebMethod]

Reply
avatar
July 28, 2015 ×

Hi..please don't alter [WebMethod]..Keep it as it is.

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..