Automatically executing HTTP POST requests in Dynamics CRM iframes

The Dynamics CRM SDK allows you to set the source URL for an iframe control on a form, and that is fine if all you need to do is load web pages that are accessible via HTTP GET requests. If you need to automatically display the results of an HTTP POST request inside an iframe, it's a bit more challenging. Today I will show an approach that I have used to implement this functionality.

This approach uses a Dynamics CRM form JavaScript library to do the following:

  1. Dynamically create an HTML form in the iframe using regular JavaScript.
  2. Dynamically append hidden form inputs with the correct parameter names and values using jQuery.
  3. Submit the form using jQuery.
function iframePost(data, url, iframename, formid) {
  //get reference to iframe using supported crm sdk approach
  var iFrame = Xrm.Page.ui.controls.get(iframename);

  //get reference to iframe guts using plain old javascript
  var iFrameDoc = iFrame.getObject().contentWindow.document;

  //overwrite anything in the iframe with an empty form
  iFrameDoc.write('<html><body><form id="'+formid+'" method="POST" action="'+url+'"></form></body></html>');

  //loop through json object attributes to add form inputs
  $.each(data, function(n,v){
    $(iFrameDoc).find('#'+formid).append('<input type="hidden" name="' + n + '" value="' + v + '" />');
  });

  //submit the form
  $(iFrameDoc).find('#'+formid).submit();
}

This function expects the parameters to be supplied to the POST endpoint as a JSON object. Here's an example of how to use it. Assume the following:

  1. The target URL for the form POST is http://example.org/testservice.
  2. "IFRAME_TESTFRAME" is the name of the iframe where you want to display the results.
  3. Input parameters are:
    1. color = 'blue'
    2. team = 'Auburn'

Your JavaScript code would look like this:

var targeturl = 'http://example.org/testservice';

var iframename = 'IFRAME_TESTFRAME';

var formid = 'myform'; //This is the id of the dynamically generated form. You can call it whatever you want.

var formparams = {};
formparams.color = 'blue';
formparams.team = 'Auburn';

iframePost(formparams, targeturl, iframename, formid);

(It should go without saying that you need to make a jQuery library available to your CRM form, too.)

And that's all there is to it. Have you needed to do anything similar in your CRM projects? What approach did you take? Please share in the comments!

comments powered by Disqus