Michael
Michael

Reputation: 2284

How to call function on parent page from iframe using jQuery?

I have an upload form that posts to a hidden iframe. I am attempting to call a function on the parent page from the iframe, but am getting the error "top.stopUpload is not a function".

What is the correct way to do this?

PARENT PAGE:

$(document).ready(function() {

    $('#document_upload').submit( function() {

        $('#upload_progress').show();

     });

    function stopUpload(success){

        if (success == 1){
            $('#result', window.parent.document).html(
            '<span class="msg">The file was uploaded successfully!<\/span>');
        }

        else {
            $('#result', window.parent.document).html(
            '<span class="emsg">There was an error during file upload!<\/span>');
        }

        $('#upload_progress').hide();

        return true;

    }

})

IFRAME:

$(document).ready(function() {

   top.stopUpload(<?php echo $result; ?>);

}

Upvotes: 4

Views: 2996

Answers (2)

jlrvpuma
jlrvpuma

Reputation: 271

Try this:

var myGlobalObject = {}; 
myGlobalObject.stopUpload = function(success){
if (success == 1){ /*...*/}
  //...
};
$(document).ready(function() {
   //...
});

From your iframe:

$(document).ready(function() {
   parent.myGlobalObject.stopUpload(<?php echo $result; ?>);
 });

Upvotes: 1

alex
alex

Reputation: 490607

Your stopUpload() function is scoped to the anonymous function you pass to $(document).ready().

You will need to ensure its scope is visible to the iframe. One way to do that would be to assign the function to window, the global object in a browser.

Another method would be to create the function in the global code, outside of that anonymous function.

Upvotes: 1

Related Questions