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 the same domain here because we are going to be using JavaScript and a little bit of PHP.
We are aware of 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 that 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>
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.
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
}
?>
There you have it. A simple way to send HTML form post data to an iFrame embedded on separate page.
Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.