0

I want to create a form using javascript and then submit that form. On the other side of the submission is an API that is programatically building a PDF for the user.

The following works in Chrome, but not IE or Firefox:

  function downloadPdf () {

    var form = document.createElement("form");
    form.setAttribute("action", "http://internal.site.com/downloadPdf");
    form.setAttribute("method", "POST");
    form.setAttribute("target", "_blank");

    form.submit();
  };

What am I doing wrong here?

And for the record, this is a simplified version of the function without all the complicated stuff that would show why I want to do it this way. :)

Pharylon
  • 9,796
  • 3
  • 35
  • 59
  • 2
    Similar to [this](http://stackoverflow.com/questions/5208224/firefox-wont-submit-a-form-created-by-javascript). – Paolo Gibellini Feb 04 '16 at 14:10
  • 1
    Like @PaoloGibellini suggested, I would go with creating the form in markup and style it's display to 'none'. No disrespect to the opinions of Marcos Pérez Gude, but I would argue the "buggy" behavior belongs to Firefox and Internet Explorer by not supporting this level of dynamic DOM creation/manipulation. – Michael Stilson Feb 04 '16 at 14:41
  • 1
    @MichaelStilson I know that Chrome is the master of the universe, but in this cases is buggy. It's like triggering a click event without intervention of the user. By security reasons that's not possible, but in Chrome it's possible... some people thinks that's the correct behaviour, but according to standards that is a incorrect behaviour. – Marcos Pérez Gude Feb 04 '16 at 15:25
  • @MarcosPérezGude I actually prefer Midori. I respect your opinions sir. I simply disagree is all. – Michael Stilson Feb 04 '16 at 15:30
  • @MichaelStilson Ok, I respect your opinion too. I prefer links2 because it renders the important content only :) . About the standards, there's no opinion, standards are writted and nobody can stay up of them. – Marcos Pérez Gude Feb 04 '16 at 15:49
  • @MarcosPérezGude yes! my kids make fun of me for using links2. :D Thanks for your words. Wish you a well day, sir. – Michael Stilson Feb 04 '16 at 16:09
  • I wish you have a nice day too! See you soon :) – Marcos Pérez Gude Feb 04 '16 at 16:10

1 Answers1

1

You can append the form in a hidden element and then submit. You can't submit anything if it doesn't exists in the DOM. Chrome is buggy, even if you think that's the correct behaviour, it doesn't.

var form = document.createElement("form");
form.setAttribute("action", "http://internal.site.com/downloadPdf");
form.setAttribute("method", "POST");
form.setAttribute("target", "_blank");
form.appendChild(document.getElementsByTagName('body')[0]); // append it
form.style.display = "none"; // hide it

form.submit();
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69