Load iframe content using POST request with angularjs

iframe can be used to embed another site on our current site. But this is done by default using a get request. In case you have to hit the server with a POST request, things might get tricky.

I had came across a scenario where i had to post around more than 50 post parameters to load a site, whose content was to be rendered into an iframe. I have written the following angularjs directive to help me generate form which will submit all these post parameters and show the content in an iframe.

Render form response in iframe

To render the form content into the iframe, we need to link the form with the iframe. To do that, we assign name to the iframe using name attribute.

<iframe width="500px" src="http://posttestserver.com/post.php" 
name="hidden_iframe"></iframe>

And this name will be used in the target property of the form.

<form method="POST" action="http://posttestserver.com/post.php"
target="hidden_iframe">
   ...
</form>

Demo

Code

<!DOCTYPE html>
<html>

  <head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="TestIframe">
    <div class="wrapper">
      <load-iframe></load-iframe>
    </div>
  </body>

</html>
angular.module('TestIframe', []).
directive('loadIframe', function ($compile, BuildForm) {
  var iframeTemplate = BuildForm.getForm() + BuildForm.getIframe();
  return {
    restrict: 'E',
    template: iframeTemplate
  }
}).
factory('BuildForm', function (DataService) {
  function getForm() {
    return generateForm('http://posttestserver.com/post.php', DataService.getData());
  }

  function generateForm(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    var form = '<form action="'+ path + '" method="POST" target="hidden_iframe">';

    for(var key in params) {
      if(params.hasOwnProperty(key)) {
        form += '<input type="hidden" name="' +key + '" value="' + params[key] + '" />'
      }
    }

    form += '<button type="submit">Click Me</button></form>';
    return form;
  }
  
  function getIframe() {
    return '<iframe width="500px" src="http://posttestserver.com/post.php" name="hidden_iframe"></iframe>'
  }

  return {
    getForm: getForm,
    getIframe: getIframe
  }
}).
factory('DataService', function () {
  function getData() {
    var data = {
      param1: 'value1',
      param2: 'value2'
    };
    return data;
  }
  return {
    getData: getData
  }
});
Hope you liked the article. If this helped you, do share this. Happy coding !!!