Monday, August 18, 2014

[JavaScript] Redirect with POST data in a new window

I recently ran into a problem where I needed to send POST data to a certain URL just like a redirect action. Below is my solution:


<html>
<html>
 <head>
  <title>Open Sesame</title>
  <script>
   function openSesame() {
    var newWindow = window.open('javascript:void(0)','_blank');
    var contents = '<html><head></head><body><form id="submitForm" method="post" action="http://mydomain.com/postdata"><input name="token" value="abcde12345678" type="hidden" /></form></body></html>';
    newWindow.document.write(contents);
    newWindow.document.close();
    newWindow.document.getElementById("submitForm").submit();
   }
  </script>
 </head>
 <body>
  <h1>Open Sesame</h1>
  <a href="javascript:openSesame()" />Open Sesame</a> 
 </body>
</html>

No comments: