How do you post to an iframe?
Asked Answered
S

5

314

How do you post data to an iframe?

Staphylorrhaphy answered 3/10, 2008 at 19:18 Comment(0)
O
462

Depends what you mean by "post data". You can use the HTML target="" attribute on a <form /> tag, so it could be as simple as:

<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!">
</form>

<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>

If that's not it, or you're after something more complex, please edit your question to include more detail.

There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.

I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.

default.asp

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <form action="do_stuff.asp" method="post" target="my_frame">
    <input type="text" name="someText" value="Some Text">
    <input type="submit">
  </form>
  <iframe name="my_frame" src="do_stuff.asp">
  </iframe>
  </body>
</html>

do_stuff.asp

<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <% if (Request.Form.Count) { %>
  You typed: <%=Request.Form("someText").Item%>
  <% } else { %>
  (not submitted)
  <% } %>
  </body>
</html>

I would be very interested to hear of any browser that doesn't run these examples correctly.

Opium answered 3/10, 2008 at 19:28 Comment(7)
As was pointed out below, the target on the form may not work in IE7—you'll want to test that.Bendicty
The problem with IE 7 is that if you generate the iframe using javascript the name tag isn't set (even if you try to set it) why the post target will fail. The solution for IE7: #2181885Olmstead
Is there a way to save the content of the output frame to a file (e.g., response from the server to which the form has been submitted) ?Scholiast
@Scholiast It's not quite clear what you mean by "save to a file". What you could do is submit the form to an IFRAME, and have the response set a Content-Disposition header as described in #1012937 - so the user clicks "submit", it posts to an IFRAME, the browser receives the response and prompts the user to save the file to their local machine. Is that what you're after?Opium
@DylanBeattie, let me clarify my usecase. I have been able to populate an iframe which has been set as the target attribute for a html <form>. After the form has been posted and I can see the content in the target iframe, I want to provide the user with an option to save this content to a file. This is what I meant to ask. Let me know if this needs more clarity.Scholiast
Let me ask 11 years later... Will src="not_submitted_yet.aspx" load that page at first into the iframe? And the content of the iframe gets replaced when the form gets submitted?Helicograph
@Helicograph exactly. If you want it blank, start with src=“about:blank” or something.Opium
H
33

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>
Heavenly answered 21/6, 2012 at 4:46 Comment(2)
Thanks, it's important that <iframe> must be after </form> as you wroteWeaverbird
Note: Google crawler heavily penalises the SERP ranking of websites when it detects elements set with 0 height/width on a page. If anyone decides to use this iframe technique, it is recommended to explicitly specify that google cannot crawl the form page via robots.txt, the page's meta robots tag and the referring page's link with rel=nofollow attribute.Aceous
S
5

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}
Segovia answered 20/5, 2018 at 19:10 Comment(0)
B
0

If you want to change inputs in an iframe then submit the form from that iframe, do this

...
var el = document.getElementById('targetFrame');

var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below

if (frame_win) {
  doc = (window.contentDocument || window.document);
}

if (doc) {
  doc.forms[0].someInputName.value = someValue;
  ...
  doc.forms[0].submit();
}
...

Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}
Breathing answered 31/10, 2018 at 22:25 Comment(0)
P
0

You can use this code, will have to add proper params to be passed and also the api url to get the data.

var allParams = { xyz, abc }

    var parentElm = document.getElementBy... // your own element where you want to create the iframe

    // create an iframe 
    var addIframe = document.createElement('iframe');
    addIframe.setAttribute('name', 'sample-iframe');
    addIframe.style.height = height ? height : "360px";
    addIframe.style.width = width ? width : "360px";
    parentElm.appendChild(addIframe)

    // make an post request
    var form, input;
    form = document.createElement("form");
    form.action = 'example.com';
    form.method = "post";
    form.target = "sample-iframe";
    Object.keys(allParams).forEach(function (elm) {
        console.log('elm: ', elm, allParams[elm]);
        input = document.createElement("input");
        input.name = elm;
        input.value = allParams[elm];
        input.type = "hidden";
        form.appendChild(input);
    })
    parentElm.appendChild(form);
    form.submit();
Pursy answered 5/1, 2022 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.