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; ?>);

}

Answers


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.


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; ?>);
 });

Need Your Help

Is there a way to test that a pointer's memory allocation has been freed?

c unit-testing pointers memory-management

Is there a way to tell that a pointer's memory assignment has been deallocated? I am just starting out in C and I think I am finally starting to understand the intricacies of memory management in C...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.