Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 11:25
AJAX Requests Get And Set Cookies Like Any Other HTTP Request
<!---
Create a response that outputs all of the cookies currently
passed in from the AJAX request. In ColdFusion, the cookie
collection is populated by the request headers.
--->
<cfsavecontent variable="responseText">
<cfoutput>
<h3>
Cookies ( as of #timeFormat( now(), "hh:mm:ss" )# )
</h3>
<ul>
<!--- Loop over the cookie collection. --->
<cfloop
item="key"
collection="#cookie#">
<!--- Only output cookies relevant to this test. --->
<cfif reFindNoCase( "^rand", key )>
<li>
#key# : #cookie[ key ]#
</li>
</cfif>
</cfloop>
</ul>
</cfoutput>
</cfsavecontent>
<!---
Now that we've created the cookie output, let's create a random
cookie to set in the current AJAX request. This will get sent
back to the client as Set-Cookie header.
--->
<cfcookie
name="rand#randRange( 111, 999 )#"
value="Woot!"
/>
<!--- Return the HTML response to the client. --->
<cfcontent
type="text/html"
variable="#toBinary( toBase64( responseText ) )#"
/>
<!DOCTYPE html>
<html>
<head>
<title>AJAX And Cookies</title>
<script type="text/javascript">
// I took this right out of the jQuery source. It creates a
// cross-browser way of creating XHR request objects.
var xhr = (
(
window.XMLHttpRequest &&
(window.location.protocol !== "file:" || !window.ActiveXObject)
) ?
function() {
return new window.XMLHttpRequest();
} :
function() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
);
// I test the AJAX request for cookie transporation.
function testAjax(){
// Create a new XHR request object.
var request = xhr();
// Open the AJAX connection.
request.open(
"GET",
("./get.cfm?_=" + (new Date()).getTime()),
false
);
// Send the request. Since this request is being made
// *Synchronously*, we don't have to keep a ready-state
// change handler.
request.send();
// Get a handle on the output node.
var output = document.getElementById( "output" );
// Append output HTML.
output.innerHTML += request.responseText;
}
</script>
</head>
<body>
<h1>
AJAX And Cookies
</h1>
<div id="output">
<!-- To be populated with AJAX. -->
</div>
<p id="tools">
<a
href="#tools"
onclick="testAjax();"
>Test AJAX Request</a>
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment