Your server code runs first so this is executed
Session["User"] = "' + userName + '";
which makes your session variable be "' + username + '". When your .net code has finished running it sends the generated html to the client, so view the source of your page and you'll see
function basicPopup(s) {
var userName = document.getElementById('txtUser').value;
'';
alert('' + userName + '');
popupWindow = window.open(s, 'popUpWindow', 'height=200,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');
}
The reason you are seeing "John" in the alert isn't because your session variable contains "John", it is because your session variable contains javascript that, when executed, shows the value of the username variable which works on that page as that variable is defined.
Basically you can't do what you're trying to do, you can run server code in your javascript. You should pass the data on the url and have page2.aspx read the value from the url and store it in the session
function basicPopup(s) {
var userName = document.getElementById('txtUser').value;
s += "?user=" + encode(userName);
In your page2.aspx;
Session["User"] = Request.QueryString["user"];