Call Server side method from JQuery in ASP.NET

Description

In this article, I am going to write different type of examples to Call Server Side method from JQuery Client Side code in ASP.NET.

Summary

Call Server Side method from JQuery in ASP.NET using JQuery ajax

   You can call server side C# method from JQuery client side using JQuery ajax method in ASP.NET.
Note: You need add reference for JQuery script file to use JQuery ajax.

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using JQuery ajax</title>
    <script type="text/JavaScript"
 src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="GetServerDate()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

   protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate()
    {
        return DateTime.Now.ToLocalTime().ToString();
    }

Call Server Side method from JQuery using JQuery ajax with Parameters

   You can call server side C# method from JQuery in ASP.NET using JQuery ajax method. Here, I have written JQuery ajax example to get current date time by passing parameters.

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using JQuery ajax</title>
    <script type="text/JavaScript" 
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"format":"' + format + '"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
            $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate(string format)
    {
        if (format.Equals("utc"))
        {
            return DateTime.Now.ToUniversalTime().ToString();
        }
        else
        {
            return DateTime.Now.ToLocalTime().ToString();
        }
    }

Call Server Side method from JQuery in ASP.NET using PageMethods

   You can call server side method from JavaScript using Ajax ScriptManager‘s PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods=”True”. Here, I have written an example to get web server time using PageMethods with Ajax call.

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using PageMethods</title>
    <script type="text/JavaScript" 
       src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [System.Web.Services.WebMethod]
   public static string GetServerDate(string format)
   {
       if (format.Equals("utc"))
       {
           return DateTime.Now.ToUniversalTime().ToString();
       }
       else
       {
           return DateTime.Now.ToLocalTime().ToString();
       }
   }

Call Server Side method from JQuery using XMLHttpRequest with Ajax call(Asynchronously)

   The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to get web server current Date Time by using XMLHttpRequest object with Ajax(Asynchronous) call.

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side C# function from JQuery using
 XMLHttpRequest with Ajax call(Asynchronously)</title>
    <script type="text/JavaScript" 
       src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {                    
                    $('#currentDate').text(xmlhttp.responseText)
                }
            }
            xmlhttp.open("Get", url, true);
            xmlhttp.send();
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

public partial class Default: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }

Note: Don’t forgot to include the line Response.Cache.SetCacheability(HttpCacheability.NoCache) to stop page cache, otherwise you will get same result from cached page.

Call Server Side function from JQuery using XMLHttpRequest without Ajax call(synchronously)

   If you want to call web server C# function as Synchronous method (without Ajax call), you need to change value true to false in the line xmlhttp.open(“Get”, url, true);

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# function from JQuery using XMLHttpRequest
 without Ajax call(synchronously)</title>
    <script type="text/JavaScript" 
         src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            $('#currentDate').text(xmlhttp.responseText)
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }

Call Server Side C# method from JQuery using XMLHttpRequest with Parameters

   You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to call C# web server side function from JQuery using XMLHttpRequest object without Ajax(Synchronous) call and Parameters.

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# method from JQuery 
using XMLHttpRequest with Parameters</title>
    <script type="text/JavaScript" 
      src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate&format=" + format;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
             $('#currentDate').text(xmlhttp.responseText)
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
    <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate(Request.QueryString["format"]);
            }
        }

        private void GetServerDate(string dateformat)
        {
            Response.Clear();
            if (dateformat.Equals("utc"))
            {
                Response.Write(DateTime.Now.ToUniversalTime().ToString());
            }
            else
            {
                Response.Write(DateTime.Now.ToLocalTime().ToString());
            }
            Response.End();
        }


Advertisement

4 thoughts on “Call Server side method from JQuery in ASP.NET”

  1. Thank you very much buddy, I searched a lot but never found this rich content with every procedure.
    I would like to ask just a favor if you can do, could you also tell what is the procedure to pass parameter and get array in return in case of HTTP Request calls to server. It will be a great help to me.

    Reply

Leave a Comment