Friday, July 15, 2011

Saving XML to Database By Way of HTTP Post

I'm not sure how to articulate this one in an interesting manner, but for the few people who come up against this, this is important information to know.  Here is how to receive XML in an HTTP Post, and put it into the database.  Once you know how to do it, it is pretty easy.  However, getting it set up is trickier than you'd think.

  1. I am processing information from a third party. They hit a specific ColdFusion cfm page with some HTTP Post parameters.
  2. One of those Post parameters contains some XML.  The XML contains the data that I am interested in.
  3. I get the XML from the HTTP Post parameters using GetHTTPRequestData().  This takes the information from the Post, and puts it into a struct.
    1. <cfset variables.parameter_raw="getHTTPRequestData()">
  4. I take the XML and pass it into xmlParse().  This parses the XML, and dumps the XML into a very usable struct.
    1. <cfset variables.parameter="xmlParse(variables.parameter_raw)">
  5. Then, before doing anything else, I dump the XML into a log file.  This way, even if everything else goes wrong, I still have a copy of the XML for debugging or whatever.
    1. <cflog file="foo" text="#serializeJSON(variables.parameter)#">
  6. Then I extract the variables I need from the XML, and pass them into a CFC.  This is the tricky part.  For some reason, if you try to pass the parameter into the CFC only by name, it will add a bunch of invisible XML stuff to it, making it too long for the database column I want to save it to.  So, in order to just get the value, without all the other wacky XML added on, add ".xmlText" to the end.  See example below:
    1. <cfset data_access_object.save_data(data_id="variables.parameter.data_idb.xmlText,
                    data_value=variables.parameter.data_value.xmlText,               data_code=variables.parameter.data_code.xmlText)>
  7. That should do it.  That ".xmlText" is really hard to debug in this context if you don't know about it.  Hopefully this will help somebody else out there.