Thursday, 23 January 2014

Call Server side method from JavaScript in ASP.NET

Description:

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

Summary:


Call Server Side method from JavaScript 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 JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = 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 JavaScript in ASP.NET using JQuery ajax

   You can call server side C# method from JavaScript 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 JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
 src="http://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) {
                document.getElementById("currentDate").innerHTML = 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 JavaScript using JQuery ajax with Parameters

   You can call server side C# method from JavaScript 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 JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript" src="http://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) {
                document.getElementById("currentDate").innerHTML = 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 JavaScript 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 JavaScript using
 XMLHttpRequest with Ajax call(Asynchronously)</title>
    <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) {
                    document.getElementById("currentDate").innerHTML = 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 JavaScript 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 JavaScript using XMLHttpRequest
 without Ajax call(synchronously)</title>
    <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);
            document.getElementById("currentDate").innerHTML = 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 JavaScript 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 JavaScript 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 JavaScript 
using XMLHttpRequest with Parameters</title>
    <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);
            document.getElementById("currentDate").innerHTML = 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();
        }

Related Articles:


Advertisements
Advertisements

15 comments:

  1. Absolutely Wonderful and knowledgeable article..Thanks Morgan

    ReplyDelete
  2. A Very good and Informative article to read...

    ReplyDelete
  3. hi, i follow exactly this method (Call Server Side function from JavaScript using XMLHttpRequest without Ajax call(synchronously))
    but it shows me error on the line :
    document.getElementById("currentDate").innerHTML = xmlhttp.responseText;

    Error: 'document.getElementById(...)' is null or not an object

    on this line my code is as : document.getElementById('txtTapeID').innerHTML = xmlhttp.responseText;

    any idea on how this error happen? thanks

    ReplyDelete
  4. Great article. Thank you!

    ReplyDelete
  5. ANy tips on how to do so in Master Page ?

    ReplyDelete
    Replies
    1. You can do the same in master page also...write a C# back-end function in any other aspx page's code behind and call it from master page.

      Delete
  6. Thank you very much. I helped a lot.

    ReplyDelete
  7. wonderful article thank u so much
    but i want to ask you .. what if i want to pass more than 1 parameter on Call Server Side C# method from JavaScript using XMLHttpRequest with Parameters part

    ReplyDelete
    Replies
    1. Hi, you can just add another query string with the url.

      var url = "Default.aspx?Arg1=val1&Arg2=val2&Arg3=val3";

      In code-behind, you can read values like below,

      Val1 = Request.QueryString["Arg1"];
      Val2 = Request.QueryString["Arg2"];
      Val3 = Request.QueryString["Arg3"];

      Delete
  8. hello,
    first of all thanks for this it is very helpful.
    I'd like to know if there is a way to give the url dynamically ? because I try your "Call Server Side function from JavaScript using XMLHttpRequest without Ajax call(synchronously)" but it seems the URL I got is wrong and may change depending on many factor (our server change depending on the connection for security reason).

    ReplyDelete
  9. Well done. Really I learn much from it. :)

    ReplyDelete
  10. The example Call Server Side method from JavaScript using XMLHttpRequest with Ajax call(Asynchronously) does not work.

    I got it to work by changing Page_Load to Page_PreInit

    ReplyDelete
  11. how to use page javascript page mthod in master page

    ReplyDelete