Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 12:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennadel/9760534 to your computer and use it in GitHub Desktop.
Save bennadel/9760534 to your computer and use it in GitHub Desktop.
Posting JSON Data To The ColdFusion Server Using jQuery
<!DOCTYPE html>
<html>
<head>
<title>Posting JSON Data To The Server Using jQuery</title>
<script type="text/javascript" src="./jquery-1.6.1.js"></script>
</head>
<body>
<h1>
Posting JSON Data To The Server Using jQuery
</h1>
<div id="response">
<!-- To be populated dynamically. -->
</div>
<script type="text/javascript">
// Define the data packet that we are going to post to the
// server. This will be "stringified" as a JSON value.
var postData = {
name: "Joanna",
hair: "Brunette",
age: 35,
favoriteMovies: [
"Terminator 2",
"The Notebook",
"Teenwolf"
]
};
// Post the data to the server as the HTTP Request Body.
// To do this, we have to stringify the postData value
// and pass it in a string value (so that jQuery won't try
// to process it as a query string).
var ajaxResponse = $.ajax({
type: "post",
url: "./api.cfm",
contentType: "application/json",
data: JSON.stringify( postData )
})
// When the response comes back, output the HTML.
ajaxResponse.then(
function( apiResponse ){
// Dump HTML to page for debugging.
$( "#response" ).html( apiResponse );
}
);
</script>
</body>
</html>
<!---
Get the HTTP request body content.
NOTE: We have to use toString() as an intermediary method
call since the JSON packet comes across as a byte array
(binary data) which needs to be turned back into a string before
ColdFusion can parse it as a JSON value.
--->
<cfset requestBody = toString( getHttpRequestData().content ) />
<!--- Double-check to make sure it's a JSON value. --->
<cfif isJSON( requestBody )>
<!--- Echo back POST data. --->
<cfdump
var="#deserializeJSON( requestBody )#"
label="HTTP Body"
/>
</cfif>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment