sun2
sun2

Reputation: 1158

Append current form data to iframe

I want to append the current form data to the iframe and submit the form within iframe instead of original form. Below is code snippet

  <script> 
   $(document).ready(function() {
    $("#imageSubmit").click(function(e) {
     e.preventDefault(); 
     $("#wrapper iframe").remove();
     $("#wrapper").append("<iframe src=''>" + $("#imageForm").html()+"</iframe>");
     $("#wrapper iframe form").submit();
     $("#wrapper iframe").load(checkStatus);
    });
   });

   function checkStatus() {
    var status = $.parseJSON($("#wrapper iframe").html());
    if (status.success) {
     alert("File " + status.filename + " uploaded!");
    } else {
     alert("Fail!");
    }
   }
  </script>

<body>
  <div id="wrapper">
   <form name="imageForm" id="imageForm" action="SOMETHING">
    <input type="file" id="imageInput" />
    <input type="submit" id="imageSubmit" />
   </form>
  </div>
</body>  

however, insted of appending the current form HTML to iframe it is adding the decoded HTML(excuse me for this word) to iframe. Here is iframe output i got:

    <iframe>
        &lt;input type="file" id="imageInput"&gt;
        &lt;input type="submit" id="imageSubmit"&gt; 
   </iframe>

Please suggest.

Upvotes: 1

Views: 4413

Answers (2)

sun2
sun2

Reputation: 1158

Thank you for your response. I did in below way, works like champ:

var iframe = "<iframe name='frame' id='frame' style='visibility:hidden' onload='onFrameLoad();'></iframe>";
$('wrapper').append(iframe);
$('#form').attr('target','frame');

function onFrameLoad(cur_form_number) {
.
.
}

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Iframes are different than other DOM elements since they create another document within the window.

The other little trick is need wait for iframe to load so use load event of iframe to add content

to work with an iframe ( same domain only) , you need to use contents(). Within contents() there is a new tree including document,html, head and body

/* dummy src to avoid same domain restrictions in some browsers*/
var jsbinIframeSrc='http://jsbin.com/evoger/1';

var $iframe=$('<iframe src="'+jsbinIframeSrc+'" width="400px" height="300px"></iframe>'); 

$("#wrapper").append( $iframe);

var $form=$('#imageForm').on('submit', function(e){
    /* demo code to show that submit works when triggered inside iframe*/
    e.preventDefault();
    $(this).replaceWith('Form was submitted');
})



$iframe.on('load', function(){
    /* unbind "load" so doesn't add form again when submitted*/
    $iframe.off('load');
     /* insert form in iframe body*/
    $(this).contents().find('body').html($form);
    $form.submit();

})

DEMO: http://jsbin.com/otobug/2/edit

API reference: http://api.jquery.com/contents/

Upvotes: 2

Related Questions