Search code examples
javascriptasp.netasp.net-session

How can I get session variable from separate JavaScript file?


I have simple code in GoogleOauth2.js file

function storedAccsessToken(token) {
    $.ajax({
        type: "GET",
        url: '<%=HttpContext.Current.Request.ApplicationPath %>/SaveToken.ashx?accToken=' + token,
        dataType: "text",
        complete: function (resp, status) {
            if (status == "success" || status == "notmodified") {
                if (resp.responseText != '');
                alert(resp.responseText);
                window.location = window.location;

            }
        }

    });

}

and

function refresh() {
    var akkToken = '<%=Session["googleAccToken"]%>';
    $.ajax({
        url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + akkToken,
        data: null,
        success: function (resp) {
            user = resp;
            alert(user.name);
        },
        dataType: "jsonp"
    });

}

when i put js file in teg head

<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
    <script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>

</head>

and when i start my project and debug js i see that <%=Session["googleAccToken"]%> compilator understand this as text but when i put js code in head tag between simple <script type="text/javascript"></script> it work fine and i get my value in session i want to know can i keep this code in separate file and that it worked fine


Solution

  • Your error is that you have include the <%= %> inside the javascript .js files, and they are not compile to give the results you expect - they stay as they are.

    There are two possible solutions to that. Ether include the variables before the javascript file, ether full move it to the page so the <%= %> can be compile. For example, you can do that :

    <head runat="server">
        <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
        <script>
           var akkToken = '<%=Session["googleAccToken"]%>';
           var UrlTo = '<%=HttpContext.Current.Request.ApplicationPath %>SaveToken.ashx?accToken=';
        </script>
        <script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>
    </head>
    

    and remove the akkToken from the GoogleOauth2.js file, and place url:UrlTo + token on the other line that also have the <%= %>