Renari
Renari

Reputation: 892

Get variable from iframe after form is submit to it?

$(function() {
    $(".preview").click(function() {
        $('#image').wrap('<form action="/index/upload.php" method="post" enctype="multipart/form-data" id="imageform" target="imageupload" />');
        $('#imageform').submit();
        $('#image').unwrap();
        var image = $('#imageupload').filename;
        return false;
    });
});

<iframe style="display: none;" name="imageupload" id="imageupload"></iframe>
<input type="file" id="image" name="image">
<input type="button" value="Preview" class="preview">

In the above code after the image is submit to the server it creates a variable in the iframe for me to retrieve containing the filename of the image uploaded. The problem I have is that when retrieving the filename jQuery's .submit() function doesn't have any callbacks when the form is submit thus while the image is uploading my code tries to get the filename when it isn't there yet. Does anyone know a way I can get around this?

Upvotes: 1

Views: 2116

Answers (1)

Renari
Renari

Reputation: 892

I found that iframes themselves have an onload event thus I was able to trigger this after submitting to the iframe and the code continues as desired after the file is uploaded.

$(function() {
   $(".preview").click(function() {
       $('#image').wrap('<form action="/index/upload.php" method="post" enctype="multipart/form-data" id="imageform" target="imageupload" />');
        $('#imageupload').attr('onload', 'preview()');
        $('#imageform').submit();
        $('#image').unwrap();
        return false;
   });
});
function preview() {
    var image = $('#imageupload').contents().find('#filename').html();
}


<iframe style="display: none;" onload="" name="imageupload" id="imageupload"></iframe>
<input type="file" id="image" name="image">
<input type="button" value="Preview" class="preview">

Upvotes: 1

Related Questions