J.F.
J.F.

Reputation: 403

Submit form into an iframe target with javascript

I'm trying to open a web page with POST and parameters into an iframe. But when submit is made the parent page is reloaded and the URL did not open into the iframe:

<head>
    <title>iframe Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
    iframe {
        display: block;       /* iframes are inline by default */
        background: #000;
        border: none;         /* Reset default border */
        height: 90vh;        /* Viewport-relative units */
        width: 90vw;
    }
    </style>
    </head>
    <body>
    <form id="myForm" method="post" action= "http://127.0.0.1/myWeb" target="myIframe">
    <input type = "hidden" name="param1" value="param1value">
    <input type = "hidden" name="param2" value= "param1value">
    </form>
     <a href="" onClick="postLogin();" >Send to iframe</a><br />
    <script laguaje="javascript">
        function postLogin() {
            var form = document.getElementById("myForm");
            form.submit();
        }
    </script>
     <iframe  src="" name="myIframe" id="myIframe">
       <p>iframes are not supported by your browser.</p>
     </iframe>
    </body>
    </html>

Upvotes: 2

Views: 15416

Answers (1)

Henrique Limas
Henrique Limas

Reputation: 317

Who is refreshing the page is the anchor tag. You can use event.preventDefault().

Change your anchor tag adding the event parameter.

<a href="" onClick="postLogin(event);" >Send to iframe</a>

And in the Javascript function postLogin add the preventDefault() event method:

    function postLogin(event) {
        var form = document.getElementById("myForm");
        form.submit();

        event.preventDefault();
    }

EDIT:

Or you can use a <button> without the postLogin function instead of the <a>.

    <form id="myForm" method="post" action= "http://127.0.0.1/myWeb" target="myIframe">
      <input type = "hidden" name="param1" value="param1value">
      <input type = "hidden" name="param2" value= "param1value">
      <button type="submit">Send to iframe</button>
    </form>

Upvotes: 5

Related Questions