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

I have a submit form that is sent to a hidden iframe. I try to call a function on the parent page from an iframe, but I get the error "top.stopUpload is not a function".

What is the right 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; ?>); } 
+4
source share
2 answers

Your stopUpload() function is bound to an anonymous function that you pass in $(document).ready() .

You will need to make sure that its area is visible to the iframe . One way to do this is to assign the window function to the global object in the browser.

Another method would be to create a function in global code outside of this anonymous function.

+1
source

Try the following:

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

From your iframe:

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

Source: https://habr.com/ru/post/1383778/


All Articles