How can I get session variable from separate JavaScript file?

9.9k views Asked by At

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

2

There are 2 answers

0
Aristos On BEST ANSWER

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 <%= %>

0
geekchic On

It's because in the latter case the javascript was processed by .NET. When the script is part of the .NET page the <%= %> tags are processed and replaced by whatever value is calculated.

When the script is an external file, it's requested by the browser separately (and even cached by the browser on subsequent page visits) and so .NET will not be processing it, resulting in the string '<%=Session["googleAccToken"]%>'.