Mike
Mike

Reputation: 1768

Cannot get filename from iframe I post to

I'm trying to upload an image using jQuery and PHP. I know there are many plugin solutions, but I'm using this. I can upload the file to the server with no problems, but for the life of me I cannot figure out how to get the file name so I can show the image. Is there any way to get the file name from the iframe I post to? Here is the code I am working with:

jquery

$('#file').change(function()
{ 
    var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
    $("body").append(iframe);
    var form = $('#form');
    form.attr("action", "../hub.php?handler=add_item");
    form.attr("method", "post");
    form.attr("enctype", "multipart/form-data");
    form.attr("encoding", "multipart/form-data");
    form.attr("target", "postiframe");
    form.attr("file", $('#file').val());
    form.submit();
    $("#postiframe").load(function()
    {
        iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
        console.log('added : '+iframeContents);                     
    });    
});

The above code outputs nothing other than the "added :" portion. Any help is greatly appreciated :)

Upvotes: 1

Views: 1493

Answers (2)

Valentin Kantor
Valentin Kantor

Reputation: 1844

You can pass some string data from iframe to main window using window.name technique. Short example of using:

Iframe:

//doing your stuff, when finished store what you need in window.name property
window.name = '{"key1":"mydata1","key2":"mydata2"}'
window.location.href='about:blank';

Main window:

$(iframe).bind('load',function(){
    //triggered every time iframe's location is changed
    var iframe_data = this.contentWindow.name;
    if(!iframe_data.length) {
      //it's a first time iframe loaded
      return;
     }
    else{
      //iframe location is changed, we're expecting to receive some data
      $(this).unbind('load');
      console.log($.parseJSON(iframe_data));
      //{"key1":"mydata1","key2":"mydata2"}
    }

})

It should work even if the iframe placed at another origin (domain). I didn't tested this code specifically, but it should work, i copypasted it from one of my projects

Upvotes: 0

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70169

You have to echo/print the filename or path from the server after the upload is complete (preferably in text/HTML as you're posting to an iframe) so you can obtain it with Javascript as in your question's code.

iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
console.log('added : '+iframeContents);

You may as well code a new JS request to fetch the uploaded images through Ajax to a new PHP (echoing JSON for example), but it's unneeded if you want to get just the uploaded file in that form submit.

Upvotes: 1

Related Questions