Solved

Accessing Variable in ASP

Posted on 2014-03-27
16
454 Views
Last Modified: 2014-05-22
In my ASP Page, I am trying to access a variable filled by User Input from a popup Box. However, for some Reason I am unable to:

<body>
      <script language="vbscript">
      Do While ID = ""
            ID = InputBox("Enter Authentication:", "Overview")
            If ID = "Close" Then
                  WScript.Quit(0)
            elseif ID = "" Then
                  WScript.Echo "Invalid Input!"
            End If
      Loop
      </script>
</body>

Later on in the body I try to output the "ID" variable but it is NULL. ANy thoughts on how I can or why I cannot get this variable value passed on after this code is finished?

Thanks
0
Comment
Question by:tr57285
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 5
16 Comments
 
LVL 53

Accepted Solution

by:
Scott Fell,  EE MVE earned 500 total points
ID: 39960573
This looks like you are trying to run client side vbscript.  You would really be better off doing this with javascript and keep the vbscript serverside.

On your pop up, is it a modal that is on the same page as everything else or is this a pop up in  different window.  

If you use a modal, it will play nicer in mobile and can be easier to code as well.  You can do this in pure javascript but here is a sample from jquery ui https://jqueryui.com/dialog/#modal-form  The sample has some validation you may not want.  But the basic idea is the form is hidden until called.  When you submit the data, you can submit to the current page and put your asp to receive in the page or submit to a new page directly or via ajax.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Dialog - Modal form</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
    body { font-size: 62.5%; }
    label, input { display:block; }
    input.text { margin-bottom:12px; width:95%; padding: .4em; }
    fieldset { padding:0; border:0; margin-top:25px; }
    h1 { font-size: 1.2em; margin: .6em 0; }
    div#users-contain { width: 350px; margin: 20px 0; }
    div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
    div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
    .ui-dialog .ui-state-error { padding: .3em; }
    .validateTips { border: 1px solid transparent; padding: 0.3em; }
  </style>
  <script>
  $(function() {
    var name = $( "#name" ),
      email = $( "#email" ),
      password = $( "#password" ),
      allFields = $( [] ).add( name ).add( email ).add( password ),
      tips = $( ".validateTips" );
 
    function updateTips( t ) {
      tips
        .text( t )
        .addClass( "ui-state-highlight" );
      setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
      }, 500 );
    }
 
    function checkLength( o, n, min, max ) {
      if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "Length of " + n + " must be between " +
          min + " and " + max + "." );
        return false;
      } else {
        return true;
      }
    }
 
    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }
 
    $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 300,
      width: 350,
      modal: true,
      buttons: {
        "Create an account": function() {
          var bValid = true;
          allFields.removeClass( "ui-state-error" );
 
          bValid = bValid && checkLength( name, "username", 3, 16 );
          bValid = bValid && checkLength( email, "email", 6, 80 );
          bValid = bValid && checkLength( password, "password", 5, 16 );
 
          bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
          // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
          bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
          bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
 
          if ( bValid ) {
            $( "#users tbody" ).append( "<tr>" +
              "<td>" + name.val() + "</td>" +
              "<td>" + email.val() + "</td>" +
              "<td>" + password.val() + "</td>" +
            "</tr>" );
            $( this ).dialog( "close" );
          }
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      },
      close: function() {
        allFields.val( "" ).removeClass( "ui-state-error" );
      }
    });
 
    $( "#create-user" )
      .button()
      .click(function() {
        $( "#dialog-form" ).dialog( "open" );
      });
  });
  </script>
</head>
<body>
 
<div id="dialog-form" title="Create new user">
  <p class="validateTips">All form fields are required.</p>
 
  <form>
  <fieldset>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all">
    <label for="email">Email</label>
    <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all">
  </fieldset>
  </form>
</div>
 
 
<div id="users-contain" class="ui-widget">
  <h1>Existing Users:</h1>
  <table id="users" class="ui-widget ui-widget-content">
    <thead>
      <tr class="ui-widget-header ">
        <th>Name</th>
        <th>Email</th>
        <th>Password</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John Doe</td>
        <td>john.doe@example.com</td>
        <td>johndoe1</td>
      </tr>
    </tbody>
  </table>
</div>
<button id="create-user">Create new user</button>
 
 
</body>
</html>

Open in new window

0
 

Author Comment

by:tr57285
ID: 39960620
Hi thanks this is a popup n the same window.
0
 
LVL 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39960980
Your question is marked as asp classic.   I think if you are trying to use client side vb, it will only work in internet explorer.

If you are using  a modal, you would have a form

<%
dim user
if request.form("user")<>"" then
' *** In production you will want to scrub your data and not take input directly ** 
   user=request.form("user")
   response.write "the form user is "&user
end if
%>


<!-- modal -->
<form action="current_page.asp" method="post">

  <input name="user">
  <button type="submit">Submit</button>
</form>

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:tr57285
ID: 39961188
Do you think I would be better off creating an ActiveX control? That way I can fetch the current logged in users ID without prompting them each time the page loads?
0
 
LVL 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39961237
Getting the logged in user is another aspect.  You don't need an activex control.  You should have either a session or encrypted cookie.

<%
session("user")="tr57285"

if request.form("something")<>"" then
' *** In production you will want to scrub your data and not take input directly ** 
   something=request.form("something")
   response.write "the form something is "&something
  
 sql="UPDATE table_name SET field1='"&something&"',fiele2='"&session("user")&"' WHERE some_column=some_value;

end if



%>

Open in new window

0
 

Author Comment

by:tr57285
ID: 39961259
Yes but a cookie would require me to have the user input their ID the first time correct? Optimally I am looking to grab the ID without having the user input any info.
0
 
LVL 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39961706
I think we are getting into a different tangent.  Perhaps how to manage log ins can be a new question topic and another discussion.

If you are taking about using the AD, there are a lot of answers here for classic asp and AD authentication.  I have a couple below but using the AD is not my area of expertise.

http://www.experts-exchange.com/Software/Server_Software/Active_Directory/Q_28077231.html#a39025197

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/Q_26611970.html#a34141448
0
 

Author Comment

by:tr57285
ID: 39961932
Ok so I am not trying to get login info.

I am just trying to get an ID from the user accessing the page because of the below:

In my page I am displaying hyperlinks that contain a userID for it to work and since the hyperlink is dependent on the current user I need the current users login ID to make the hyperlinks work.

I think the issue here is that when I call the function and prompt the user for their ID it is run client side:

<head>
<script language="JavaScript">
		function checkCookie()
		{
			ID=getCookie("username");
			if (ID!="")
  			{
  				return ID;
  			}
			else 
  			{
  				ID = prompt("Please enter your name:","");
  				if (ID!="" && ID!=null)
   		 		{
    					setCookie("username",ID,365);
    				}
  			}
		}
</script>
</head>

<body>
	<script language="VBScript">
		ID=javascript:checkCookie()
	</script>
TBPLink = ID
</body>

Open in new window


From the VBScript code I can get the returned ID variable from the Javascript function, but once I leave the VBScript code and return to my body I can no longer access that variable which is what I need to do.

I am trying to access the variable from within the middle of my HTML code but by that point it is no longer available.
0
 
LVL 33

Expert Comment

by:Big Monty
ID: 39964962
just make the variable global or use a hidden form field to store the value:

<head>
<script language="JavaScript">
        var ID = 'some default value';    //-- you don't need to set a default one, i am just so you make sure the right value displays below

		function checkCookie()
		{
			ID=getCookie("username");
                        //-- or you could use a hidden form field
                        document.getElementById('hdnUserName').value = getCookie("username")

			if (ID!="")  //-- or if you're using the hidden form field, you would replace ID with  document.getElementById('hdnUserName').value
  			{
  				return ID;
  			}
			else 
  			{
  				ID = prompt("Please enter your name:","");
                                //-- same thing here, just replace all references of ID with the hidden form field
  				if (ID!="" && ID!=null)
   		 		{
    					setCookie("username",ID,365);
    				}
  			}
		}
</script>
</head>

<body>
<input type="hidden" name="hdnUserName" id="hdnUserName" value="some default value if you want" />

	<script language="VBScript">
		ID=javascript:checkCookie()
	</script>
TBPLink = ID
</body>

Open in new window


the advantage of using a hidden form field over a global variable isn't great, you just don't have to worry about scope; you can access it from anywhere on the page.
0
 
LVL 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39965063
You can request the same cookie via js or vb.  http://www.w3schools.com/asp/asp_cookies.asp

The basic scenario below assumes you have a stored cookie for the username, but the user is not logged in.  This allows us to just ask for a password.  Or you may have done a two step log in where the user already entered the user id in a previous page, but the password is not authenticated.

The vbscript here is serverside.

Notice no need to have the user id in a hidden field because we already have the cookie.

The sample below is very basic for testing but should not be used in production as it assumes the password is not encrypted and your cookie data has not been encrypted as well.  For the password, by encrypted, I actually mean hashed.  

<%
userID=Request.Cookies("username") 'get the cookie

if request.form("password")<>"" then  ' test if form submit
     ' create recordset of users
     sql = "SELECT password, userLevel from table users WHERE user_id ="&userID 
     ' assume recordset called rsUser is created
     
     if not rsUser.bof or not rsUser.eof then
          session("LoggedInUser")=userID
          session("UserLevel")=rsUser("userLevel")
          else ' set logged in session info to nothing
          session("LoggedInUser")=""
          session("UserLevel")=""   
     end if

end if

%>
<form>
<input name="password">
<button type="submit">Submit</button>
</form>

Open in new window

0
 
LVL 33

Expert Comment

by:Big Monty
ID: 39966502
Notice no need to have the user id in a hidden field because we already have the cookie.

and what happens if there is no cookie, or it just hasn't been set yet? that's what the code looked like from the original question. this solution makes too many assumptions and seems to be go off on a tangent on what the OP was asking...
0
 

Author Comment

by:tr57285
ID: 39966849
Thank you all for contributing thus far.

Optimally what I am looking to do is not involve the user at all.

I would like to get the current logged in user (by grabbing an environmental variable) from the users machine and using that to modifying my page. Is this possible without the users intervention?

Would I need an ActiveX for this or is there another option?
0
 
LVL 33

Expert Comment

by:Big Monty
ID: 39966941
how does the user log in? through Active Directory? if so, you can do

request.servervariables("LOGON_USER")

to get the current logged in user. This assumes that anonymous login is turned off in IIS
0
 

Author Comment

by:tr57285
ID: 39967087
Hi Big Monty, Thanks

My site uses a service account currently, so the user is not prompted to login to the site, but Anonymous logon is also not turned on.

Is there a way to enable Basic Authentication on a page by page basis?
0
 
LVL 33

Expert Comment

by:Big Monty
ID: 39967120
I believe Request.ServerVariables("LOGON_USER") will work for you. try creating a simple script like this:

Response.Write Request.ServerVariables("LOGON_USER")

if you get the service account, then you know that's the right server variable
0
 
LVL 33

Expert Comment

by:Big Monty
ID: 40083537
no split on the points?

sheesh! i answered a bunch of your secondary questions and gave good advice on how to handle the passing of the variable
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question