How to check if a POST submitted field exists in VBScript? - asp-classic

After a form is submitted, how does one check server-side if a particular field exists? For example:
If [Exists] Request("FieldName") Then
...
End If

If Request("FieldName").Count > 0 Then
...
End If
Or, for short:
If Request("FieldName").Count Then
...
End If
Background:
The Request collection is magic, in so far as it does not throw an error when you try to access a key that was not part of the request - but the .Count will be 0 for non-existing keys.
In a URL-encoded query string it's legal to send keys that don't have a value, like foo&bar&baz
It's also legal to send the same key multiple times, i.e. multiple values per key, like foo=value1&foo=value2.
Therefore, the reliable way to determine if a key has been sent by the client is to count how many times the client has sent it.
A special case of this test is checking whether there was a non-empty value for that key (If Request("FieldName") > ""). This may or may not be what you want in the end; just be aware that the underlying behavior of query strings is broader than that.

Check if it's not empty. There are a few different ways, but the one I've seen more frequently used is along the lines of:
If Request("FieldName") <> "" Then
'etc.
End If
I usually explicitly check the Form and QueryString collections with some variation of one of the code below if I may be getting the variable from one or the other depending on context:
Select Case True
Case Request.Form("FieldName") <> ""
'Run if the Form isn't empty
Case Request.QueryString("FieldName") <> ""
'Run if the QueryString isn't empty
Case Else
'Set a predefined default if they're both empty
End Select
Or a nested If ... Then:
If Request.Form("FieldName") <> "" Then
'Run if the Form isn't empty
ElseIf Request.QueryString("FieldName") <> "" Then
'Run if the QueryString isn't empty
Else
'Set a predefined default if they're both empty
End If
If I know exactly which collection it's coming from, I'll check that collection specifically. The reason is that I want to make sure it is pulling what I expect from where I expect it to come from. I don't want someone overriding a Form value by sending something in the QueryString when I'm not expecting it.
From MSDN:
If the specified variable is not in one of the preceding five
collections, the Request object returns EMPTY.
All variables can be accessed directly by calling Request(variable)
without the collection name. In this case, the Web server searches the
collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
If a variable with the same name exists in more than one collection,
the Request object returns the first instance that the object
encounters.
It is strongly recommended that when referring to members of a
collection the full name be used. For example, rather than
Request.("AUTH_USER") use Request.ServerVariables("AUTH_USER"). This
allows the server to locate the item more quickly.

To check if the parameter was present (without caring about its value) it is also possible to write:
fieldValue = Request("FieldName")
if Not IsEmpty(fieldValue) ...
One advantage over Count method above is, that you can test the variable, without referring to the field name again.
Advantage over testing for "" is that if you pass &FieldName without assigning value, test for "" will yield true, but IsEmpty returns false.
Edit: Turns out this is not reliable in IIS.
For the url with ?param alone, or ?param=&param2, IsEmpty(param) returns false, but
For the url with ?param&param2, IsEmpty(param) weirdly returns true ...

I usually check the value of the SUBMIT button. If it was clicked, it's value is posted along with the form data. So, even if all your form data is blank, the submit button's value will not be. And if the submit button's value is blank, then it wasn't clicked.
if request("btn_Submit") <> "" Then
response.write "form was submitted"
end if
This is more difficult if you are using a javascript form.submit() call, in which case I usually opt for the hidden field.

Related

What does an empty input's value when using POST in asp?

I am using asp (JScript as my language) and working with getting data from a form that is sent using POST.
Specifically, I have a text input and I want to check if it was left empty. When leaving it empty, and including Response.Write(Request.form('opt2Dur')) in the called page, nothing prints (doesn't print null or undefined).
My thought was that it was just an empty string so I included this: Response.Write(Request.form('opt2Dur') === ''), however this printed false.
It will print true if I use Response.Write(Request.form('opt2Dur') == '') (== not ===). What is the true value that I can check against using ===? Or, in this case will it be sufficient to check with just ==?
Thanks for any help.
In scripting languages with "flexible" types and default values it's very easy to get confused with actual data types.
The actual type of each Request item (both QueryString and Form, it doesn't matter) is some sort of Array as it also supports more than one form element with the same name submitted to the ASP handler. It's mentioned in the documentation as well:
The Form collection is indexed by the names of the parameters in the request body. The value of Request.Form(element) is an array of all the values of element that occur in the request body.
Since the === also take into account type, it will return false in your case as array is not a string.
I wasn't able to find the exact actual type and reproduce it with local variable (it's not any plain array) so if you are keen on using the strict comparison operator, check the Count:
Response.Write(Request.Form('opt2Dur').Count === 0);

IndexOutOfBounds when executing a NamedQuery twice

I'm trying to make a web application for the first time, and I use all kinds of tutorials and help of any kind, but I don't get why this happens. Everything worked all right until now:
I'm trying to transmit a "User" attribute between servlets, and I'm doing so by sending part of it as an attribute (using RequestDispatcher or HTML forms), and looking up the rest of it in a database, like this:
String user = (String) request.getAttribute("txt");
Users info = (Users) emf.createEntityManager().createNamedQuery("Users.findByUsername").setParameter("username",user).getResultList().get(0);
Username is Unique key, and the code for the NamedQuery is
#NamedQuery(name = "Users.findByUsername", query = "SELECT u FROM Users u WHERE u.username = :username)
The first time I use this, it works and I get the expected result, but, if I come back to the same servlet or I use the same code again in other servlet, I get java.lang.IndexOutOfBoundsExpcetion: Index: 0, Size: 0
How can this happen if I didn't modify the database at any moment?
Any help would be appreciated.
Seems like your request attribute "txt" is null the second time. It's a request attribute, so it will be only valid during the request. If you don't store it or submit it every time it will be null.
A null as username will produce an empty list. The attempt to read the first element of an empty list produces the IndexOutOfBoundsException.
Use a session attribute or resubmit the attribute every time and it will work.

Passing a parameter through server.execute?

It is possible to pass a parameter through server.execute?
Fx. I have in my site.asp an IF-scenario where I need functions.asp?a=something&id=123 executed. Is this possible?!
On site.asp:
dim id
id = 123
if b = "hi" then
server.execute("functions.asp?a=something&id=" & id)
else
response.write("No way dude")
end if
On functions.asp
a = request.querystring("a")
id = request.querystring("id")
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
You can't use querystring in Server.Execute, it's clearly mentioned in the official documentation.
What you can do is much better: you can directly access the variable id defined in site.asp inside functions.asp, and you can also declare and set another variable, a:
--site.asp:
dim id, a
id = 123
a = "something"
server.execute("functions.asp")
--functions.asp
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
As it creates whole new "scripting environment" the executed file won't have access to the calling code properties, methods or variables, only to the global Request parameters, Session etc.
With this in mind, I fear the most simple way around is using Session variable to pass the value between pages:
Session("id") = 123
Session("a") = "something"
And then:
if Session("a") = "something" and Session("id") > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
This question may be old and resolved, but the best answer doesn't mention everything, and there is information clearly posted on Microsoft.com about it:
Server.Execute Method
The following collections and properties are available to the executed ASP page:
Application variables, even if they are set in the calling page.
Session properties, even if they are set in the calling page.
Server variables and properties, even if they are set in the calling page.
Request collections and properties, even if they are set in the calling page. This includes Form and QueryString data passed to the calling page.
Response collections and properties. The executed .asp file may modify HTTP headers. However, as with any .asp file, if the executed .asp file attempts to modify HTTP headers after it sends a response to the client, it generates an error.
So as you can see, there are 5 ways Microsoft suggests to pass variables through to a Server.Execute method. Before I saw this on Microsoft, the preferred method was Session, as the best answer suggests, since I saw this before the info on Microsoft.com. But after noticing that QueryStrings can be passed from the previous page, I would have to say this beats using Session for passing values. Session would be needed if your application required you adding variables to the executing page.
But passing variables, I would say QueryStrings, and it's easy to apply if your application allows the flexibility. I'm sure you know how to already use querystrings, but in the sense of using it for a Server.Execute method, you can simply do this:
Consider having ASP1.asp and ASP2.asp:
ASP1.asp includes:
Server.Execute("ASP2.asp")
ASP2.asp includes:
Response.Write Request("id")
When you call ASP1.asp?id=123
You will notice that ASP2.asp also see's the same Querystring passed to ASP1.asp, so it would write 123 on the response of ASP1.asp.
That's much less complicated than using a Session for the task.
In short: YES, you can use QueryString values in conjunction with Server.Execute within an ASP.NET page or application.
You can pass dynamic variables in a QueryString argument assembled in the executing ASPX page (page1.aspx), as follows:
Dim intExample1 As Int = 22
Dim strExample2 As String = "hello world"
Server.Execute("page2.aspx?number=" & intExample1 & "&string=" & Server.UrlEncode(strExample2))
In this example, page2.aspx can then reference and use the following values:
Request.QueryString("number")
Request.QueryString("string")
Why not to use #include instead of server.execute?
I looked for a difference and found that in this particular case, using #include is the best solution:
https://en.wikibooks.org/wiki/Active_Server_Pages/Server-Side_Includes#What_it_Does
You need some variables defined in parent page to be used in child, so your solution could be:
dim id, a
id = 123
a = "something"
if b = "hi" then
<!--#include file="functions.asp" -->
else
response.write("No way dude")
end if
On functions.asp
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
Advantages:
Simply act as it was the same page.
Use of disposal variables instead of Session variables.
Don't show internal variables in main URL.

get special value in url

url:http://localhost:51806/fair/PersonPage/personalPages.aspx?idCompany=1338006699#Site/AboutAs
request["idCompany"];
this code return null
how can get value idCompany
EDIT
Request.UrlReferrer.Query
this return ?idCompany=1338006699
this Request.UrlReferrer.Query.Split('=')[1] return 1338006699
but i think this way does not good way
#Site/AboutAs is a tab aboutAs in full tab component
Try this instead:
string id = Page.PreviousPage.Request.QueryString["idComapny"];
If no luck then your method of splitting is the best you can achieve, as you're trying to read the query string of the referrer page.
One work around though is to store the value in that previous page.
To do this, store the value of Request["idComapny"] in the previous page, where it should be available, in Session then you can read the Session value in any other page.

Check if an Object exists in VBScript

I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.
I have an array of imagefile paths, like so:
dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"
This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).
If Not banners Is Nothing then
' then loop through the Dictionary and make a list of image links
End if
The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error
What's the proper way to check if an object exists in VB Script?
#Atømix: Replace
If Not banners Is Nothing then
and use
If IsObject(banners) Then
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
#Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)
IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised.
To summarize:
IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised
IsNull(var) will test if a variable has been assigned to Null
var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object
IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty).
If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function:
Dim banners
If IsEmpty(banners) Then
Response.Write "Yes"
Else
Response.Write "No"
End If
' Should result in "Yes" being written
banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing.
You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems.
edit: I just saw this related question and answer which might help, too.
Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this:
Sub FooBar(Optional oDoc As Object)
'if parameter is missing then simulate it
If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something
...
You need to have at least dim banners on every page.
Don't you have a head.asp or something included on every page?
Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered.
The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here:
Is there any way to check to see if a VBScript function is defined?

Resources