Wednesday, 16 April 2014

Set Session value in JavaScript

Description:

In this article, I am going write examples to access and set Session variable Value in JavaScript and how to Set Session variable value from JavaScript in ASP.NET using PageMethods, XMLHttpRequest and JQuery Ajax call.

Summary:


Set Session value in JavaScript using PageMethods

You can get and set 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 set and get session value in JavaScript using PageMethods.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key,string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session Value from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">

        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            PageMethods.SetSessionValue('UserName', userName, null, null);
        }

        function GetUserName() {
            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>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Set Session value in JavaScript using XMLHttpRequest in ASP.NET

You can set and get 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 get and set session value in JavaScript in ASP.NET using XMLHttpRequest.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Method"] == "SetUserName")
        {
            SetUserName(Request.QueryString["Value"].ToString());
        }
        else if (Request.QueryString["Method"] == "GetUserName")
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            GetUserName();
        }
    }

    private void SetUserName(string userName)
    {
        Session["UserName"] = userName;
    }

    private void GetUserName()
    {
        Response.Clear();
        if (Session["UserName"] != null)
        {
            Response.Write(Session["UserName"].ToString());
        }
        else
        {
            Response.Write("Session Value not found");
        }
        Response.End();
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session variable value in JavaScript using XMLHttpRequest</title>
    <script type="text/javascript">
        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;            
            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 = "WebForm1.aspx?Method=SetUserName&Value=" + userName;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);                     
        }

        function GetUserName() {
            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 = "WebForm1.aspx?Method=GetUserName";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("lbUserName").innerHTML = xmlhttp.responseText;
        }
 
    </script>
     
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Get and Set Session value in JavaScript using JQuery ajax call

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

Check the below example to set 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)
    {
    }

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session value 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 SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/SetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName","value":"' + userName + '"}',
                success: function (result) {
                    //Session value saved successfully
                },
                error: function (xhr, status, error) {
                    //Failed to save Session value
                }
            });
        }

        function GetUserName() {
            $.ajax({
                type: "post",
                url: "WebForm3.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>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Advertisements
Advertisements

No comments:

Post a Comment