Get Session value in JavaScript

Description

In this article, I am going explain how to Access or Check Session Value in JavaScript and how to Access Session variable from JavaScript in ASP.NET using XMLHttpRequest, JQuery Ajax call and PageMethods.

Summary

Get Session value in JavaScript

To get or access session variable value in JavaScript you can use following JavaScript code:

var userName = '<%= Session["UserName"] %>'

Check the below example to get session variable value in JavaScript and set it for welcome label.

Default.aspx.cs:

  public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["UserName"] = "Administrator";
        }
    }

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get Session Value in JavaScript</title>
    <script type="text/javascript">
        window.onload = function () {
            var userName = '<%= Session["UserName"] %>'
            document.getElementById("lbUserName").innerHTML = userName;
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Welcome,
        <label id="lbUserName">
        </label>
    </div>
    </form>
</body>
</html>

Get Session variable value from JavaScript using XMLHttpRequest in ASP.NET

You can get or access server side session variable value from JavaScript in ASP.NET using using XMLHttpRequest. The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can access Server Side value from JavaScript client side by using this object without refreshing or reloading the page.

Check the below example to check session value in JavaScript in ASP.NET using XMLHttpRequest.

Default.aspx.cs:

   protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetLoginUser")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetLoginUser();
            }
            else
            {
                Session["UserName"] = "Administrator";
            }
        }

        private void GetLoginUser()
        {
            Response.Clear();
            Response.Write(Session["UserName"].ToString());
            Response.End();
        }

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Get Session variable value in JavaScript using XMLHttpRequest</title>
    <script type="text/javascript">
        function GetLoginUser() {
            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=GetLoginUser";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("lbUserName").innerHTML = xmlhttp.responseText;
        }
 
    </script>
     
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Logon UserName" onclick="GetLoginUser()" />
    <label id="lbUserName">This is currently logged in username</label>
    </div>
    </form>
</body>
</html>

Check Session value in JavaScript using PageMethods

You can get or access session variable value from JavaScript in ASP.NET using Ajax ScriptManager‘s PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods=”True”.

Check the below example to access session value in JavaScript using PageMethods.

Default.aspx.cs:

  protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = "Administrator";
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        return HttpContext.Current.Session[key].ToString();
    }

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Get Session Value from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">
        function GetLoginUser() {
            PageMethods.GetSessionValue('UserName', OnSuccess, OnFailure);
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        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 User Name" onclick="GetLoginUser()" />
        <label id="lbUserName">
            This is currently logged in user name</label>
    </div>
    </form>
</body>
</html>

Check Session value in JavaScript using JQuery ajax call

You can access or get session variable value from JavaScript in ASP.NET using using JQuery ajax method.

Check the below example to get session variable value in JavaScript using JQuery ajax call.
Note: You need add reference for JQuery script file to use JQuery ajax method.

Default.aspx.cs:

  protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = "Administrator";
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        return HttpContext.Current.Session[key].ToString();
    }

Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Get Session value from JavaScript 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 GetLoginUser() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        function OnFailure(error) {
            alert(error);
        }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show User Name" onclick="GetLoginUser()" />
        <label id="lbUserName">
            This is currently logged in user name</label>
    </div>
    </form>
</body>
</html>


Advertisement

5 thoughts on “Get Session value in JavaScript”

  1. Hi there! Would you mind if I share your blog with my facebook
    group? There's a lot of folks that I think would really appreciate
    your content. Please let me know. Thanks

    Reply

Leave a Comment