removing default document from current URL - vbscript

I use the following code to get the URL of current page.
thispage ="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL") & "?" & Request.Querystring
I want to check if user has typed the default document (index.asp) at the end of URL and remove it (by redirecting to the clean URL without default document in address bar).
But this code always contains the default document even when if not typed in address bar e.g. the code above returns http://example.com/index.asp when I have http://example.com in address bar.
How do I edit the above code to distinguish those URLs?

It's a complicated task in an environment where you don't know what the applicable default document is but I think it's always index.asp in your case.
If so, you can do it with something like the following.
defaultFile = "/index.asp" ' leading slash is mandatory
reqUrl = Request.ServerVariables("URL")
reqQS = Request.ServerVariables("QUERY_STRING")
'put a leading question mark if there's a query
If reqQS <> "" Then
reqQS = "?" & reqQS
End If
'check if URL ends with "/index.asp" (case-insensitive comparison should be made)
If StrComp(Right(reqUrl, Len(defaultFile)), defaultFile, vbTextCompare) = 0 Then
' remove from reqUrl by preserving leading slash
reqUrl = Left(reqUrl, Len(reqUrl) - Len(defaultFile) + 1)
End If
thispage = "http://" & Request.ServerVariables("SERVER_NAME") & reqUrl & reqQS

you can do soemthing like:
url = Request.ServerVariables("URL")
url = Left( url, Len( url, Right( url, InStrRev( url, "/" ) - 1 )
thispage ="http://" & Request.ServerVariables("SERVER_NAME") & url & "/?" & Request.Querystring

Related

Classic ASP - Cannot Get Request.Form Values from AJAX Post Request

I have a script that is submitting a POST request of a form via AJAX.
When I look at the network tab, it is coming back in the format below, which I cannot read with a standard Request.Form in Classic ASP. I am seeing this server variable added to the page request as well due to the AJAX request: HTTP_X_REQUESTED_WITH = XMLHttpRequest
The form is set up as a simple POST: <form method="post" action="/contact-submit">
I cannot change the script performing the AJAX request to update the content type, etc.
This is the “Request payload” in the response on the network tab below. I have googled for days and cannot figure this out. How do you access this data? I even tried reading it with a file upload script I have via ASPUpload, but Upload.Form("contact_name") does not work either, it's blank as well.
I tried a simple PHP script (I do not know how PHP works, but this script came with script performing the POST as a demo), and calling print_r($_POST) the script passes all the correct info in an array back in the response on network tab. What the heck!!
Does anyone know how to get this data back in Classic ASP?
Thanks so much for the help in advance.
Dennis
-----------------------------254001430938683980861095915686
Content-Disposition: form-data; name="contact_name"
Test Name
-----------------------------254001430938683980861095915686
Content-Disposition: form-data; name="contact_email"
test#test.com
-----------------------------254001430938683980861095915686
Content-Disposition: form-data; name="contact_message"
my message
-----------------------------254001430938683980861095915686--
I worked on a solution to reading the data, this works below. Not sure it is the best / least expensive way to do this, but it works!
Thanks to everyone for the help / tips. If anyone has a better way to parse the response above, I'm all ears :)
<%
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
If Request.TotalBytes > 0 Then
Dim lngBytesCount, post
lngBytesCount = Request.TotalBytes
post = BytesToStr(Request.BinaryRead(lngBytesCount))
End If
Response.ContentType = "text/plain"
sContentType = Replace(Request.ServerVariables("CONTENT_TYPE"),"multipart/form-data; boundary=---------------------------","")
arrPost = Split(post,"-----------------------------" & sContentType)
For i = 0 to UBound(arrPost)
sVal = Replace(arrPost(i),"Content-Disposition: form-data; name=","")
arrVal = Split(sVal,Chr(10),1)
For a = 0 to UBound(arrVal)
If Instr(1, arrVal(a), "contact_name") <> 0 Then
Response.Write GetValue(arrVal(a), "contact_name")
End If
If Instr(1, arrVal(a), "contact_message") <> 0 Then
Response.Write GetValue(arrVal(a), "contact_message")
End If
Next
Next
Function GetValue(f_FullString, f_FieldName)
fieldval = Replace(f_FullString, """" & f_FieldName & """","")
'response.Write "_" & fieldval & "_<Br>"
arrVal1 = Split(fieldval,Chr(10),1)
For b = 0 to UBound(arrVal1)
newval = arrVal1(b)
newval = Left(newval,Len(newval) - 2)
newval = Right(newval,Len(newval) - 6)
'For z = 1 to Len(newval)
' CurrChar = Mid(newval, z, 1)
' Response.Write Asc(CurrChar) & "<bR>"
'Next
Next
GetValue = newval
End Function
%>
UPDATE:
This is another solution if you have ASPUpload installed. I tried this last night, but forgot to add Upload.Save (which would have saved me 4hours of work --- UGGGGGHHHH).
'http://www.aspupload.com/manual_memory.html
Set Upload = Server.CreateObject("Persits.Upload")
Upload.Save
Name = Upload.Form("contact_name")
Response.Write Name

Getting Microsoft VBScript runtime error '800a0009' on Checkout Cart

I'm really not very familiar with ASP, but the site I'm managing is spitting that error out to me. Here is the full code from the site:
Microsoft VBScript runtime error '800a0009'
Subscript out of range: '[number: 1]'
/shopping_sub.asp, line 715.
Here is the code from 697-728:
'Response.write strPass & "<p>"
'Response.write "Response: " & strResp
'Response.end
If strResp="ERROR" then
RESULT_num_shipping_options = -1
Session("ShipErrMsg")="To continue your order, please contact customer service regarding your contact information. Thank you."
Else
RESULT_num_shipping_options=1
vResp=Split(strResp,":")
Dim RESULT_shipping_description_array(4)
Dim RESULT_shipping_amount_array(4)
For I = 0 to UBound(vResp)
vResp2=Split(vResp(I),"|")
RESULT_shipping_description_array(I)=vResp2(0)
RESULT_shipping_amount_array(I)=vResp2(1)
Next
End If
Else
RESULT_num_shipping_options = -1
cShipping=0
End If
End If
'Response.write "Weight: " & siWeight & "<br/>"
'Response.write "Zip: " & receiverpostalcode & "<br/>"
'Response.write "Country: " & receivercountrycode & "<br/>"
It appears to start functioning after 7 items have been added to the cart, but anything less than that returns errors.
This doesn't happen with all products, so any idea?
Have you used a debugger to determine the value of vResp and the array length of vResp2?
My guess is that the response is not what you expected. If you can't force the api to always have the correct response, then you'll want to protect against it by checking the length of the split response before trying to access the value.
Another problem I see that is unrelated, is that if the UBound(vResp)_ > 4, then you'll get a similar error

Issue running Classic ASP written in VBScript on Windows 2012 with IIS 8

This is a very peculiar issue. I have a 2012 Server running IIS 8 with support for classic ASP installed. I am building a comma separated string from a form. I then am retrieving this string from a table and want to split on the commas.
First, when I build the string and submit it to the DB (SQL Express 2014), something is adding a space after each comma even though there is no space in the code.
Second, when I return the string and attempt to split on the comma, it doesn't do anything; the ubound method returns -1... For testing purposes, I hand built an array and this has the same behavior.
Code that builds the csv string:
If fieldName = "txt_EnvironmentType" then
strTempEnvCSV = strTempEnvCSV & fieldValue & ","
End If
Test code for split:
txtEnvironmentType = "This,Is,A,Test,String"
If txtEnvironmentType <> "" then
response.write(txtEnvironmentType)
array = split(txtEnvironmentType,",")
l = ubound(array)
response.write("<br>array is " & l & " long")
For i = LBound(array) to UBound(array)
response.write("<br>" & array(i))
Next
End If
The Above test code returns the following to the browser:
This,Is,A,Test,String
array is -1 long
Am I missing something?
Thanks!
For the mysterious spaces, add a TRIM() to make sure you aren't starting with spaces:
If fieldName = "txt_EnvironmentType" then
strTempEnvCSV = strTempEnvCSV & TRIM(fieldValue) & ","
End If
This ran (for your second issue) for me - the only change I made was to dim the array variable and name it something other than "array"
<%
dim arrMine
txtEnvironmentType = "This,Is,A,Test,String"
If txtEnvironmentType <> "" then
response.write(txtEnvironmentType)
arrMine = split(txtEnvironmentType,",")
l = ubound(arrMine)
response.write("<br>arrMine is " & l & " long")
For i = LBound(arrMine) to UBound(arrMine)
response.write("<br>" & arrMine(i))
Next
End If
%>

How can I strip the element using vbscript and display in message box?

I would like to find the price with 2 year contract and display it in a message box. Sofar I have:
Dim MyPage
Dim Price
Set MyPage=CreateObject("Microsoft.XMLDOM")
MyPage.load("http://www.verizonwireless.com/b2c/store/controller?item=phoneFirst&action=viewPhoneDetail&selectedPhoneId=5723")
Wscript.Sleep 2000
Set Price = MyPage.getElementsByTagName("span")
For Each Elem In Price
MsgBox(Elem.firstChild.nodeValue)
Next
I understand that I am completely wrong, but I don't even know where to start. I love writing simple programs like this, but I just need help getting started. Any ideas will help!
Here a better version, uses the HTMLFile object
Dim HTMLDoc, XML, URL, table
Set HTMLDoc = CreateObject("HTMLFile")
Set XML = CreateObject("MSXML2.XMLHTTP")
URL = "http://www.verizonwireless.com/b2c/store/controller?item=phoneFirst&action=viewPhoneDetail&selectedPhoneId=5723"
With XML
.Open "GET", URL, False
.Send
HTMLDoc.Write .responseText
End With
Set spans = HTMLDoc.getElementsByTagName("span")
for each span in spans
WScript.Echo span.innerHTML
next
'=><SPAN>Set Location</SPAN>
'=>Set Location
'=><SPAN>Submit</SPAN>
'=>Submit
'=>Connect with us
the control you use is for reading XML documents, you need something like this
'Create an xmlhttp object, the string depends on the version that is installed
'on your pc could eg also be "Msxml2.ServerXMLHTTP.5.0"
Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.Open "GET", "http://admin:pasword#10.0.0.2/doc/ppp.htm", False
xmlhttp.Send
text=xmlhttp.responseText
wscript.echo text
Set xmlhttp = Nothing
Run a search in your registry for XMLHTTP to get the right string/version for the identifier.
To get the tag from the html you can use the following
text = "blabla <span>this is what i need</span> bla bla<span>second item</span> end"
function getElementsByTagName(sTextToSeachIn, tag)
answer = ""
separator = ""
set oRegExpre = new RegExp
with oRegExpre
.IgnoreCase = true
.Global = true
.MultiLine = True
.Pattern = "<" & tag & ">(.*?)</" & tag & ">"
end with
set oColMatches = oRegExpre.Execute(sTextToSeachIn)
for each match in oColMatches
answer = answer & separator & match.subMatches(0)
separator = "|" 'use something that's not in the spancontents
next
if separator <> "" then
getElementsByTagName = split(answer, separator)
else
getElementsByTagName = array()
end if
end function
for each tag in getElementsByTagName(text, "span")
wscript.echo tag
next
'=>this is what i need
'=>second item
There are better techniques and certainly better languages than vbscript to do this, i suggest to take a look at Ruby which exels in such things.
Alex, in response to your comment about getting a cookie and running a javascript in HTMLFile, here a ruby script i found, hopes it helps you at some point, it reads in a page, passes it to the HTLMFile object and in that DOM executes a remote javascript file. It also gives you an idea of the combined power of activeX and Ruby.
require "win32ole"
$jsxpath_uri = "http://svn.coderepos.org/share/lang/javascript/javascript-xpath/trunk/release/javascript-xpath-latest-cmp.js"
uri, xpath = "http://gist.github.com/gists", "//div[#class='info']/span/a"
http = WIN32OLE.new('MSXML2.XMLHTTP')
http.Open "GET", uri, false
http.Send
text = http.responseText
dom = WIN32OLE.new("htmlfile")
dom.Write(text)
dom.parentWindow.eval(open($jsxpath_uri){|f| f.read })
items = dom.evaluate(xpath, dom, nil, 7, nil)
len = items.snapshotLength
(0...len).each do |i|
item = items.snapshotItem(i)
puts item.innerHTML
end

Update a database record without refreshing a page. ASP VBscript

This requests for help follows a poorly worded request for help earlier (apologies).
I have two asp/vbscript pages. The second page (containing only <% vbscript %> is called when a form on the first page is submitted.
The code on the second page causes an update to a database record and is as follows (the fields are populated from querystring variables.):
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET " & fieldPrefix & "has_text1 = 'YES', " & fieldPrefix & "text = '" & fieldUpdate & "' WHERE id = " & tempid & ""
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
All the form submit does is to cause the database update to happen - nothing else.
The page then response.redirects back to the calling page. This causes a refresh and lot of data on the first page to be lost - this is what I'm trying to avoid.
Can someone please tell me how I can carry out the update without leaving and then refreshing the calling page please? I've been told Ajax can do this but I have no experience at all of using it.
Many thanks
First of all, change your code to use parameters so you will be protected against SQL Injection attack:
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET " & fieldPrefix & "has_text1 = 'YES', " & fieldPrefix & "text = ? WHERE id = ?"
Set MyCommand = Server.CreateObject("ADODB.Command")
Set MyCommand.ActiveConnection = MyConn
MyCommand.CommandType = 1
MyCommand.CommandText = SQLString
MyCommand.Parameters.Append(MyCommand.CreateParameter("#text", 200, 1, 0, fieldUpdate))
MyCommand.Parameters.Append(MyCommand.CreateParameter("#id", 3, 1, 0, tempid))
MyCommand.Execute()
MyConn.Close
Set MyCommand = Nothing
Set MyConn = Nothing
Having this, the next step is adding hidden frame in the first page:
<iframe id="MyFrame" name="MyFrame" style="display:none;"></iframe>
And finally simply add target to your <form> tag like this:
<form action="SecondPage.asp" target="MyFrame">
That's it... now the form will be submitted "inside" the hidden frame, will still trigger the database update and won't cause any refresh.

Resources