How to read json respone field value in classic asp - json

Please help me to read json response filed value in classic asp.
For example:
I am getting below response in classic asp. I require deliveryNo and content value. Please help on this:
{"labels":[{"shipmentID":"a2f3vh3","deliveryNo":"1234","content":"test","invoice":null,"responseStatus":{"code":200,"message":"SUCCESS","messageDetails":"All shipments processed and label/invoice generated successfully","logMsg":[]}}],"responseStatus":{"code":200,"message":"SUCCESS","messageDetails":"All shipments processed successfully","logMsg":[]}}

At the risk of annoying people by answering something that has been answered already lots of times, I use a solution which used to be available via http://www.aspjson.com/, but the site seems to be down now.
I still use the code though - it's here http://pastebin.com/qvn2UxXV
This is a very simple example of how to use it with your data, to get at deliveryNo and Content:
<!--#INCLUDE file="aspJSON.asp" -->
<%
Set oJSON = New aspJSON
jsonstring = "{""labels"":[{""shipmentID"":""a2f3vh3"",""deliveryNo"":""1234"",""content"":""test"",""invoice"":null,""responseStatus"":{""code"":200,""message"":""SUCCESS"",""messageDetails"":""All shipments processed and label/invoice generated successfully"",""logMsg"":[]}}],""responseStatus"":{""code"":200,""message"":""SUCCESS"",""messageDetails"":""All shipments processed successfully"",""logMsg"":[]}}"
Set oJSON = New aspJSON
oJSON.loadJSON(jsonstring)
For Each result In oJSON.data("labels")
Set this = oJSON.data("labels").item(data)
var_deliveryNo = this.item("deliveryNo")
var_content = this.item("content")
response.write "deliveryNo: " & var_deliveryNo & "<br />"
response.write "content: " & var_content & "<br />"
Next
%>

You could use ASPJSON
aspjson is JSON serializer for VBScript based ASP server technology.

Related

Classic Asp Generate and Validate Anti Forgery Token

I have been stuck in this topic for a long time and I hope someone can help me.
I have an application written in asp classic. I must implement an antiforgery token in the form where I go to validate the data.
My page is composed like this
<% Dim token
token = GetGUID()
Session("token")=token
%>
<html>
<head>
</head>
<boby>
...
...
<form method="post" action="../includes/CENT_FUNCTIONS.ASP">
<input type="hidden" value="<%=Session("token")%> name="token">
</form>
</body>
</html>
As you can see at the top in the asp code when opening the page I generate a GUID that I am going to save in a session variable.
I generate the GUID with this vbs function
FUNCTION GetGUID()
GetGUID = CreateObject("Scriptlet.TypeLib").GUID
END FUNCTION
So I'm going to save the session variable in a hidden field of the form. The action of the form goes to call another asp file where I will go to collect the form data to call a store procedure in the sql database.
The file is written like this
<%
IF Request("token") = Session("token") THEN
ID_CENT=Request.QueryString("ID_CENT")
IDAZIENDA_CENT=Request("IDAZIENDA_CENT")
ELSE
Response.Redirect "../notallowed.asp"
END IF
set command = Server.CreateObject("ADODB.Command")
command.ActiveConnection = conn
command.CommandText = "CAR_CENTRALINI_FUNZIONI"
command.CommandType = adCmdStoredProc
set objParameter = command.CreateParameter ("#ID_CENT", adInteger, adParamInput,,ID_CENT)
command.Parameters.Append objParameter
set objParameter = command.CreateParameter ("#IDAZIENDA_CENT", adInteger, adParamInput,,IDAZIENDA_CENT)
command.Parameters.Append objParameter
command.Execute , , adExecuteNoRecords
Set command=Nothing
Set objParameter=Nothing
Response.Redirect "../Fonia/UT_Fonia_CENTRALINI.asp"
%>
So before collecting the form data I go to check if the token arrived is the same as the one stored in the session variable.
But this comparison that I make in the IF condition always returns false.
Is this way I am using to generate and validate the anti forgery token correct? What am I doing wrong?
Thanks for any replies

scrape html source vba

I need to scrape some info from web, using vba. This is an extract of my code. It's ok, but the site has 2 classes with the same name. So my code writes only the last value. I want that:
Sheets("01").Range("DW" & number) = source.getAttribute("data-id")
writes only the first value of class "sample" found on site.
How can I do?
Thanks
With http
.Open "GET", site, False
.send
html.body.innerHTML = .responseText
End With
For Each source In html.getElementsByClassName("sample")
Sheets("01").Range("DW" & number) = source.getAttribute("data-id")
Next source
Next number
You can be more efficient by using querySelector, which only returns the first match rather than an entire collection (or nodeList)
Sheets("01").Range("DW" & Number) = html.querySelector(".sample").getAttribute("data-id")
To refer to the first element of a class collection, you can use the Item property, for which the index is 0-based. So you can replace your For Each/Next with the following line...
Sheets("01").Range("DW" & Number) = html.getElementsByClassName("sample").Item(0).getAttribute("data-id")
Hope this helps!

VBS to get an Element from a web page is not working properly

I want to get the value '24' in my VBS, which is set in the div with id 'test'. My HTML is:
<html><body>
Welcome <br /> Value: = <div id="test">24</div>
<br> Name: <p id="name">Someone</p><br>
</body></html>
And my VBS is:
on error resume next
set ie=createobject("internetExplorer.Application")
ie.navigate "http://localhost/h/getid.html"
ie.visible = false
wscript.sleep 2000
dim val
set val =ie.document.getElementsById("test").item(1).value
wscript.echo "value is= "& val
But the output does not show the value "24", it is just echoing
value is=
How can I get that value?
You should not ask a question here that concerns a script with an active "On Error
Resume Next". That is a waste of everybody's time. By not hiding errors/Pay attention to
error messages, you can solve the problem(s) on your own (most of the time).
Delete/Deactive the OERN and you get
set val =ie.document.getElementsById("test").item(1).value
==>
... runtime error: Object doesn't support this property or method: 'ie.document.getElementsById'
Even if you don't recognize the typo, a google search for "html dom getelementsbyid"
will re-route you to "Ergebnisse für [i.e. results for] html dom getelementbyid".
Follow one of the first links (e.g.) to refresh you knowledge about that method.
That way the next error:
set val =ie.document.getElementById("test").item(1).value
==>
... runtime error: Object doesn't support this property or method: 'ie.document.getElementById(...).item'
won't surprise you. An element isn't a collection of items/elements. [BTW: You shouldn't
post answers here without at least basic tests].
The next version
set val =ie.document.getElementById("test").value
should raise a red alert: An assignment with Set, but a right value that wants to be a
property of an object. That is blantantly wrong. So try:
set elm =ie.document.getElementById("test") ' at least a decent assignment
val = elm.value
==>
... runtime error: Object doesn't support this property or method: 'elm.value'
A google query like "html dom div text" will point you to "innerText"
and its features: 1 or 2
At last:
set elm =ie.document.getElementById("test") ' at least a decent assignment
val = elm.innerText
success!
cscript 23971918.vbs
value is= 24
It looks like you need change getElementsById with getElementById.
Someone mentioned you should change the getElementsById to getElementById (no 's'), but I also think you should lose the .item(1) in this line:
set val =ie.document.getElementsById("test").item(1).value
If I'm remembering correctly, using .item(#) would be appropriate if your object was a collection, like something returned by using .getElementsByTagName but .getElementById should only return one item.
Hope that helps!

How to update web page by sending POST request with parameter to it AND get the last retrieved paramter value by sending GET request to it

I need to write a simple web page that can be update by POST of a parameter:
Sending POST request to the page with a parameter - will update the web page constantly.
Sending GET request to the page will return the last retrieved value of the parameter
For example (Probably each request is a different session):
POST /mypage.asp?param1=Hello
GET /mypage.asp >> Response: Hello
POST /mypage.asp?param1=Changed
GET /mypage.asp >> Response: Changed
Use $_SESSION
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST")
$_SESSION['last_val'] = $_POST['some_val'];
}
if($_SERVER['REQUEST_METHOD'] == "GET")
echo $_SESSION['last_val'];
}
Learn more about SESSION
Evan's answer is correct conceptually, but I think he doesn't address the different sessions and didn't use "classic ASP" (vbscript or jscript).
To persist a value between sessions and requests, you need some form of storage. Probably the simplest option is an Application variable (which I show below). Other options are "thread-safe" storage, like the widely available CAPROCK DICTIONARY, or a database.
The code:
<%# Language="VBScript" %>
<%
If Request.ServerVariables("REQUEST_METHOD")= "POST" Then
Application.Lock
Application("StoredValue") = Request.Form("param1")
Application.Unlock
Else
Application.Lock
Response.Write Application("StoredValue")
Application.Unlock
End If
%>
<%
dim fileSystemObject,Text_File,Text_File_Content,NewValue
NewValue=Request.QueryString("MyParam")
set fileSystemObject=Server.CreateObject("Scripting.FileSystemObject")
If NewValue <> "" Then
set Text_File=fileSystemObject.CreateTextFile("C:\MyPath\myTextFile.txt")
Text_File.write(NewValue)
Text_File.close
End If
if fileSystemObject.FileExists("C:\MyPath\myTextFile.txt")=true then
set Text_File=fileSystemObject.OpenTextFile("C:\MyPath\myTextFile.txt",1,false)
Text_File_Content=Text_File.ReadAll
Text_File.close
else
set Text_File=fileSystemObject.CreateTextFile("C:\MyPath\myTextFile.txt")
Text_File.write("Please send GET request to this page with paramter MyParam!")
Text_File.close
set Text_File=fileSystemObject.OpenTextFile("C:\MyPath\myTextFile.txt",1,false)
Text_File_Content=Text_File.ReadAll
Text_File.close
end if
Response.Write(Text_File_Content)
%>

Accessing a request's body using classic ASP?

How do I access what has been posted by a client to my classic ASP server?
I know that there is the Request.Forms variable, but the client's request was not made using a Form.
The client request's body is just a string made using a standard POST statement.
Thanks
You need to read request bytes if content type of request sent by client is not form data. In this case, request is not a form-data that is accessible through name-value pairs so you cannot use Request.Form collection. I suggest investigate the BinaryRead method.
Reading posted data and convert into string :
If Request.TotalBytes > 0 Then
Dim lngBytesCount
lngBytesCount = Request.TotalBytes
Response.Write BytesToStr(Request.BinaryRead(lngBytesCount))
End If
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
Hope it helps.
Update #1:
With using JScript
if(Request.TotalBytes > 0){
var lngBytesCount = Request.TotalBytes
Response.Write(BytesToStr(Request.BinaryRead(lngBytesCount)))
}
function BytesToStr(bytes){
var stream = Server.CreateObject("Adodb.Stream")
stream.type = 1
stream.open
stream.write(bytes)
stream.position = 0
stream.type = 2
stream.charset = "iso-8859-1"
var sOut = stream.readtext()
stream.close
return sOut
}
To get the JSON string value just use CStr(Request.Form)
Works a treat.
In Classic ASP, Request.Form is the collection used for any data sent via POST.
For the sake of completeness, I'll add that Request.QueryString is the collection used for any data sent via GET/the Query String.
I would guess based on the above that even though the client is not a web browser, the Request.Form collection should be populated.
note: all of this is assuming the data being sent is textual in nature, and that there are no binary uploads (e.g. pictures or files) being sent. Update your question body if this is an incorrect assumption.
To test, write out the raw form data and see what you have - something along the lines of:
Response.Write(Request.Form)
Which with a regular web page will output something like
field=value&field2=value2
If you get something along those lines, you could then use that as a reference for a proper index.
If you do not get something like that, update your question with what you tried and what you got.