Frames and forms

Webmasters are advised to not use frames as they put a barrier in the way of crawlers of search engines among other drawbacks such as security issues.

But for a Web application, you may need for frames and it is useless that robots index the pages.

In fact there is a surprising return of frames on big sites: Google (Image Search, for example), Digg (for the toolbar), Stumbleupon and Facebook among others.
The process has its advantages and disadvantages.

Drawbacks include the inability to natively send form data between the frames in a frameset. But we'll see how it can be bypassed.

Data are exchanged between frames through the window object

A set of two frames is defined:

<frameset rows="300,*">
<frame src="frame1.html" name="topFrame" id="topFrame" />
<frame src="frame2.html" name="bottomFrame" id="bottomFrame" /> </frameset>

To pass information between frame1 and frame, we make use of:

window.top

To which we associate the name of the frame, and the path to an item, for example:

window.top.topFrame.document.getElementById("frame2"); 

To test that, we create a form in each frame to enter text, and a field to display text taken from the other frame.

In the top frame, we will insert data from the bottom frame into the element whose id is frame1.

<div id="frame1">Empty </div>

The JavaScript code in the bottom frame reads the value from a text field and sends it to the top frame via window.top:

function sendit()
{
var content = document.form2.mytext.value;
window.top.topFrame.document.getElementById("frame1").innerHTML = content; }

It is associated to the onclick event of a button:

 <input type="button" name="Submit" value="Send to top" onclick="sendit()" />

The same goes for sending data from the top frame to bottom, as you can see in the source code of the demonstration...

Form data are exchanged between frames through PHP

If you want to use the attribute "action" of the form and send its data to another page, you can pass through the page containing the frameset, but it must then add the parameters in the URL of frames, for example with PHP code:

<frameset rows="300,*">
<frame src="frame1.html<?php parameters();?>" name="topFrame" id="topFrame" /> <frame src="frame2.html" name="bottomFrame" id="bottomFrame" /> </frameset>

The PHP function that retrieves and transmits the data is very simple:

function parameters()
{ $login=$_POST['login']; $password=$_POST['password']; if(!empty($login))
{ echo "?login=$login&password=$password"; }
}

We can generalize the code by getting all keys in $_POST and all values, and then forming a chain beginning with the code "?" with the key-value pairs separated by "&".

© 2009-2012 Xul.fr