Search code examples
javascriptasp-classicglobal-variablesenvironment-variablesserver-side

Server-Side JS in ASP implications


I was trying to use JavaScript as a scripting language in a classic-ASP website. I came across several errors. Many JS objects would not work and also some constants. Can someone explain the implications of using JavaScript as a server-side scripting language. This is my first attempt at a JavaScript powered asp website, so I have provided this code.

<%
var user = Request.QueryString("name");
Response.Cookies("thisUser") = user;

var expdate = new Date(Date.now().setMinutes(Date.now().getMinutes()+5));
Response.Cookies("thisUser").Expires = expdate.toString();

function _greet(name) {
    Response.Write("<p>And also you... <b>" + name + "</b> ...I guess...</p>");
}

%>
<!doctype html>
<html>
<head><title>ASP</title></head>
<body>
<%
Response.Write("<p>Hello World!</p>");
if (user != undefined) {
    _greet(user);
}
%>
</body>
</html>

_greet() always runs regardless of whether user is undefined. expdate.toString() causes internal server error due to not returning a string of date type. It just returns the number and toDateString() is not supported! And is there any way to debug JavaScript in ASP?

P.S. I already set the default language to JavaScript in the server manager(IIS 8.5). Also I am just testing as an intranet site.


Solution

  • If you are checking to see if the cookie is being set, you have to read the cookie and check if it really expires in the set 5 minutes.

    The .Expires setting seems to expect the date formatted as yyyy-MM-dd H:m format.(I am not sure if this is the ONLY format it accepts, you could try different variations)

    <%@ Language= "JavaScript" %> 
    <%
    
    var user = Request.QueryString("name");
    
    //set the cookie only if it is not undefined
    if(user+"" != "undefined")
    {
        //write the name to cookie
        Response.Cookies("thisUser") = user;
    
        var fiveMinutesLater = new Date();
        fiveMinutesLater.setMinutes(fiveMinutesLater.getMinutes() + 5);
    
        //Response.Cookies("thisUser").Expires seems to expect the date in yyyy-MM-dd H:m format
        var formatteddate= fiveMinutesLater.getFullYear()+ "-" +("0" + (fiveMinutesLater.getMonth()+ 1)).slice(-2)+ "-" + ("0" + fiveMinutesLater.getDate()).slice(-2)+ " " + ("0" + fiveMinutesLater.getHours()).slice(-2)+":"+("0" + fiveMinutesLater.getMinutes()).slice(-2)
    
        Response.Cookies("thisUser").Expires = formatteddate;   
    }
    
    
    function _greet(name) {
        Response.Write("<p>And also you... <b>" + name + "</b> ...I guess...</p>");
    }
    %>
    <!doctype html>
    <html>
    <head><title>ASP</title></head>
    <body>
    <%
    Response.Write("<p>Hello World!</p>");
    
    //Read the cookie.
    var thisUser = Request.Cookies("thisUser");
    
    if (thisUser != "") {
        _greet(thisUser);
    }
    %>
    </body>
    </html>