How to Post Web Forms to an iFrame on Another Page

iFrame on Another Page

We recently discussed how to post HTML form data to an iFrame. But we saw that the solution we provided only works if the iFrame is on the same page as the form.

This time around we decided to show you how you can do the same thing. This time we will be targeting an iFrame embedded on another web page on the same domain. We stress same domain here because we are going to be using JavaScript and a little bit of PHP.

We are aware about the cross domain scripting restrictions that come with JavaScript that restrict us from applying this solution to an iFrame loaded from another domain.

Setting to Target an iFrame on Another Web Page

The first page is a simple HTML file which will hold the form that we will use to submit the respective data. The form can be something simple like this.

Page 1 code

<form action="Page2.php" method="post">
<label for="text">Input Label:</label>
<input type="text" name="text" id="text">
<input type="hidden" name="page2control" value="authorized">
<input type="submit" value="Submit">
</form>

view raw
post-form.html
hosted with ❤ by GitHub

We will then create another page that can be processed server side. Aside from processing the post data from the form, this file will be used to create a mirror of the form from the first page only this time it will change the target to the iFrame which is now embedded on the same file.

Read Also  How to Install the Latest phpMyAdmin on Ubuntu 20.04

The page will then be pushed back to the browser with some JavaScript code tied to it. When the JavaScript is executed, it will resubmit the form and the browser will target the iFrame as desired. Here is some code to illustrate.

Page 2 code

<?php
// validate input is from the form.
// Note: no other validations have been done
if ($_POST["page2control"] == "authorized")
{
?>
<form id="page2form" target="iframe-name" method="post" action="process-form-data.php">
<input name="text" value="<?= $_POST['text'] ?>">
</form>
<!– the javascript to repost the form –>
<script type="text/javascript">
$(function(){
$("#page2form").submit();
});
</script>
<?php
}
?>

view raw
Page2.php
hosted with ❤ by GitHub

There you have it. A simple way to send HTML form post data to an iFrame embedded on separate page.