Link to home
Start Free TrialLog in
Avatar of tnelson217
tnelson217

asked on

Using XMLHTTP and preserving session variables

I have found a few posts on this topic and have tried to follow the suggestions in the posts but have not been successful.

I am trying to use XMLHTTP to build a page.  The end result is that I want to append several pages together and then print them.  But for now I'm just trying to get it work with one page, putting the generated page text into a variable.  I'll build from there once I get this working.  However, I am having a problem with getting past my site's authentication.  I saw a few posts on this same issue, and decided to try to send the cookies on the request header.  Here is the code that I have (my actual URL chagned to protect the innocent).

I log into the application, navigate to the point at which I would be running this when it is working, then load this page (test_print_2.asp) and I get the login page instead of the page I want to build.  So it is not recognizing the session variables.  Any ideas as to what I'm doing wrong?

I will post a separate comment with a link to the EE post that sent me in this direction.

=====================================================
<%@ Language = VBScript %>
<%
Response.Buffer = True
Dim objXMLHTTP, xml, myVariable

' Create an xmlhttp object:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

' Call the page
objHTTP.Open "GET", "http://mydomain/myapp/mypage.asp?q_type=Current", False
objHTTP.setRequestHeader ("cookie") = Request.Cookies
' Put this in twice due to MS bug
objHTTP.setRequestHeader ("cookie") = Request.Cookies
objHTTP.Send

myVariable = objHTTP.responseText
 
Set xml = Nothing
%>
<html>

<body>

Saved into variable.

The contents of the xml variable:  
<%=myVariable%>
</body>
</html>
Avatar of tnelson217
tnelson217

ASKER

Hey, I don't know where my scroll bar was when I read that post I just referred to; I only looked at the first "green" response but upon rereading it I see that was the assisted answer.  The accepted answer was further down the line and was a much more involved approach.  I'm still interested in anything anyone wants to suggest and meanwhile I will also try to figure out what the other post is suggesting (didn't fully understand it on my first scan of it.)

I should also point out that this is all (classic) ASP.  Another salient point; I need all the session variables, not just the login authentication stuff; the page(s) I am calling through the XML call will need some session variables in order to function properly.

OK, I'll stop posting to my own question after this one.

I looked more at that accepted answer and it is specifically talking about the back-and-forth to login to a remote site.  I think my situation is different.  I'm working within my own site.  The user is already logged in and has made some other selections that are also stored in session variables.  I need all that session information to be available when I call the page via XMLHTTP.  So my question (after all that) is really:

How can I get all the session information cleanly over to the context of the XMLHTTP call?  Can I loop through the session vars and send them one by one?  Perhaps something like this?

For Each Key in Session.Contents
            objHTTP.SetRequestHeader Key, Server.htmlencode(Session.Contents(Key))
Next    

Alright, I'll stop blathering on and will sit back and wait for an answer.  Thansk for reading this far!
To post variables to a page that uses Request.Form(xxx) to get the values do the following:

Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", "http://mydomain/myapp/mypage.asp?q_type=Current", False
objHTTP.Send "var1_name=var1_value&var2_name=var3_value"
myVariable = objHTTP.responseText

Using cookies only complicates the matters! But if you still insist on using them then include the following in your code:

<%@ Language = VBScript %>
<%
Response.Buffer = True
Dim objXMLHTTP, xml, myVariable

' Create an xmlhttp object:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

' Call the page
objHTTP.Open "GET", "http://mydomain/myapp/mypage.asp?q_type=Current", False
objHTTP.setRequestHeader ("cookie") = ""
' Put this in twice due to MS bug
objHTTP.setRequestHeader ("cookie") = GetCookies(xmlhttp.getAllResponseHeaders())
objHTTP.Send

myVariable = objHTTP.responseText
 
Set xml = Nothing
%>
<html>

<body>

Saved into variable.

The contents of the xml variable:  
<%=myVariable%>
</body>
</html>
<%
'   DO NOT MODIFY THE FOWLLOWING CODE
'***************************************'
'**                   Dinit Softwares              **'
'**              Author: Prakhar Birla              **'
'**         visit www.dinitsoftwares.com        **'
'***************************************'
Function GetCookies(Header)
      cookieString=""
      Temp = Split(Header,vbCrlf)
            for i=0 to UBound(Temp)
            HeadTag=""
            On Error Resume Next
            HeadTag = Mid(Temp(i),1,11)
                  if HeadTag="Set-Cookie:" then
                  CookieContent=""
                  HeadCookie = Mid(Temp(i),12,Len(Temp(i)))
                  HeadCookieEnding=InStr(1,HeadCookie,";")
                        if HeadCookieEnding=0 then
                        CookieContent=HeadCookie
                        else
                        CookieContent=Mid(HeadCookie,1,HeadCookieEnding-1)
                        end if
                  cookieString = cookieString & CookieContent & ";"
                  end if
            next
GetCookies=cookieString
End Function
%>
Oh! I forgot one line in the previous code:

Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", "http://mydomain/myapp/mypage.asp?q_type=Current", False
objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.Send "var1_name=var1_value&var2_name=var3_value"
myVariable = objHTTP.responseText

Some form are posed using "multipart/form-data" for them use the following instead of objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded":

objHttp.setRequestHeader "Content-Type", "multipart/form-data"
I do need the session variables, even if they make it more difficult.

So I am trying the second (longer) suggested code snippet.

I get this error:
msxml3.dll error '80072f76'
The requested header was not found
/dev3/payline/test_print_3.asp, line 11

and line 11 is:
objHTTP.setRequestHeader ("cookie") = ""

My bad! I shouldn't have copied your code! The syntax of the setRequestHeader method was wrong! And there was a logical error. Here's the new code (read through the comments)

<%@ Language = VBScript %>
<%
Response.Buffer = True
Dim objXMLHTTP, xml, myVariable,newCookies

' Create an xmlhttp object:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

'Sign-in into whatever page you want like:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", "http://mydomain/myapp/login.asp", False
objHTTP.Send "var1_name=var1_value&var2_name=var3_value"
''''IMPORTANT the page will return cookies to the browser! and you have to save them so that you can pass them on to other pages as if you were the browser!
newCookies = GetCookies(objHTTP.getAllResponseHeaders())

' Now get the other page
objHTTP.Open "GET", "http://mydomain/myapp/mypage.asp?q_type=Current", False
objHTTP.setRequestHeader "Cookie", "Cool=Me" 'This should not be blank just put anything here
objHTTP.setRequestHeader "Cookie", newCookies
objHTTP.Send

myVariable = objHTTP.responseText
 
Set xml = Nothing
%>
<html>

<body>

Saved into variable.

The contents of the xml variable:  
<%=myVariable%>
</body>
</html>
<%
'   DO NOT MODIFY THE FOLLOWING CODE
'*******************************************'
'**            Dinit Softwares              **'
'**        Author: Prakhar Birla          **'
'** visit www.dinitsoftwares.com **'
'******************************************'
Function GetCookies(Header)
      cookieString=""
      Temp = Split(Header,vbCrlf)
            for i=0 to UBound(Temp)
            HeadTag=""
            On Error Resume Next
            HeadTag = Mid(Temp(i),1,11)
                  if HeadTag="Set-Cookie:" then
                  CookieContent=""
                  HeadCookie = Mid(Temp(i),12,Len(Temp(i)))
                  HeadCookieEnding=InStr(1,HeadCookie,";")
                        if HeadCookieEnding=0 then
                        CookieContent=HeadCookie
                        else
                        CookieContent=Mid(HeadCookie,1,HeadCookieEnding-1)
                        end if
                  cookieString = cookieString & CookieContent & ";"
                  end if
            next
GetCookies=cookieString
End Function
%>
Thanks for the quick response!  Having read through all the comments, I do have a follow-up question:

I can safely assume that whenever this page is run, the user is already logged in.  I want to be able to preserve all the session variables (that show me the context of the user within the application at the time they are running the page), not only the login stuff.  If I rerun the login page as suggested in the code you just posted, the other session vars will be lost because the user context will be reset.  Is there a way that I can fetch the cookies without doing this:

'Sign-in into whatever page you want like:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", "http://mydomain/myapp/login.asp", False
objHTTP.Send "var1_name=var1_value&var2_name=var3_value"
''''IMPORTANT the page will return cookies to the browser! and you have to save them so that you can pass them on to other pages as if you were the browser!
newCookies = GetCookies(objHTTP.getAllResponseHeaders())

In other words, can I assign newCookies from the current environment rather than by creating the xmlHTTP object to the login page?  And then continue with the rest of your code from there?
Just use this instead of the code you gave in your last comment.

newCookies = ""
For each Item in Request.Cookies
newCookies = newCookies & Item & "=" & Request.Cookies(Item) & "&"
Next
If Not(Len(newCookies)=0) then
newCookies=Mid(newCookies,1,Len(newCookies)-1)
End If
'Now new cookies contains all the cookies that the current user has in his browser
OK, now I've got the code you have provided working fine, but it does not solve my problem.  The cookie string comes through fine and I get no erros on any of the xml statements.  But I still get the login screen instead of the page that I want.  The login_ID is not in the cookies, it is in a session variable.

What I really want to preserve (or I guess more accurately you would say I want to mimic it or send it) is the session; the Session(login_ID) field plus others.  I am calling a page that refers to
several session variables as Session("varName") and I need that page to work without change.

I know how to loop through the session variables, so I tried to do that, with the following within the loop:
            objHTTP.SetRequestHeader Key, Server.htmlencode(Session.Contents(Key))

but that did not change anything; I still get the login page.

Am I trying to do the impossible?  I have seen several posts asking to do what I am trying to do, and none of them seem to have real solutions posted.

I will reduce this to a simple example and post.

 

Here is a sample calling page.  I am sending the cookies and trying to send one session variable.

<%@ Language = VBScript %>
<%
Response.Buffer = True
Dim objHTTP, myVariable, newCookies

' Create an xmlhttp object:
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
' Get the other page
objHTTP.Open "GET", "http://myserver/myapp/Test_Print_target.asp", False

' Create the cookie string
newCookies = ""
For each Item in Request.Cookies
    newCookies = newCookies & Item & "=" & Request.Cookies(Item) & "&"
Next
If Not(Len(newCookies)=0) then
    newCookies=Mid(newCookies,1,Len(newCookies)-1)
End If
'Now newCookies contains all the cookies that the current user has in his browser
' Send the cookies
objHTTP.setRequestHeader "Cookie", "Cool=Me" 'This should not be blank just put anything here
objHTTP.setRequestHeader "Cookie", newCookies

' Set the session variable
Session("sendSession") = "hello world"

' Transfer the session variable
objHTTP.SetRequestHeader "sendSession", Server.htmlencode(Session.Contents("sendSession"))

' Send the page
objHTTP.Send

' Set the variable to the contents of the page
myVariable = objHTTP.responseText
 
Set xml = Nothing
%>
<html>

<body>
The contents of the cookies:
<%=newCookies%>

Saved into variable.

The contents of the xml variable:  
<%=myVariable%>
</body>
</html>
And here is the target page:

<%@ Language = VBScript %>
<%
Response.Buffer = True
%>
<html>

<body>

This is the target page and the session variable is:  <%=Session("sendSession")%>.

</body>
</html>
And here is what currently happens when I run the calling page:
(I added some <br>'s after posting the code above, but that's all that I changed.)
*****************************

The contents of the cookies: BIGipServerPool_Dev_Asp_App=1563559946.20480.0000&SITESERVER=ID=21f0935eea13d10df125428965af2b10

Saved into variable.

The contents of the xml variable:
This is the target page and the session variable is: .

Hey!
The core you are using to add the session variable is not correct. I'm trying to investigate how session's work so please be patient.
ASKER CERTIFIED SOLUTION
Avatar of DinitSoftwares
DinitSoftwares

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sure thing.  Patience is no problem.  Thanks for the effort!



Ah, so much for that idea.  As things progressed I worried that that was the case.  And the way you stated it, it does seem obvious.  Basically I'm trying to start a new session (via XML) and keep the old session.  Can't have your cake and eat it too.

But it was worth a try and I learned a lot in the process.  I will give you the points and accept the answer that says it is not possible, which adds to the knowledge base here on EE, since lots of other posts that I found just sort of ended inconclusively.

I will go back to the drawing board as far as my original task, but thanks for all the effort and information!
You are welcome! And thanks for the points!