0

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)
})
Silverburch
  • 457
  • 2
  • 12
  • 28
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – StudioTime Aug 29 '17 at 12:12
  • I'm afraid that most of the content in that post goes right over my head! I'd appreciate some simpler direction. – Silverburch Aug 29 '17 at 12:21
  • Only there isn’t really one. You have to embrace the fact that with today’s JavaScript you are working in a largely event-driven environment; if you try to “fight” that, you won’t get very far. The point where you are currently outputting your “This alert should NOT appear last” message __is__ the right place to handle the data you just asynchronously received. – CBroe Aug 29 '17 at 12:27
  • Thanks, that's useful guidance – Silverburch Aug 29 '17 at 12:38

0 Answers0