Spent 2 days analysing so many posts on this but just can't get anything to work. From my parent page I'm loading an iframe which contains a database. Once loaded that database automatically runs and passes a list of countries back to the parent page in a variable called 'AllCountries'. All this works well. But what I want is to use the variable elsewhere in my code. In other words I'm trying to get the last line in my jQuery to list the countries. But jQuery processes this line too soon, well before the countries have been assigned to the variable. I've tried putting the events into functions, using callback, etc, but didn't seem to work. Any ideas? Fiddle http://jsfiddle.net/8sgh01hc/
https://code.jquery.com/jquery-1.12.4.min.js
<iframe id="Z_test" src="https://c2ect538.caspio.com/dp.asp?AppKey=b8a94000f5fb0d287ec840b89679"></iframe>
$(function() {
var AllCountries = ""
$("#Z_test").load(function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to message from child IFrame window
eventer(messageEvent, function (e) {
AllCountries = e.data;
alert('This alert should NOT appear last ' + AllCountries);}, false);
alert('iFrame loaded!');
});
// ---------------
alert('This should be the LAST alert appearing with countries list' + AllCountries)
})