0
$.getJSON("../../index.php/churchlocator/base", function(data) {
    base_url = data.base;
}); 
alert(base_url);

How can I get base_url in the above code to be accessible outside of the getJSON var?

Michael Grigsby
  • 9,179
  • 9
  • 31
  • 49

1 Answers1

2

The right answer here is to put all code that references the result of the ajax call in the success handler for the ajax call. Do not use global variables for this:

$.getJSON("../../index.php/churchlocator/base", function(data) {
    var base_url = data.base;
    alert(base_url);
    // or you may call some other function here and pass it the data
    myFunction(base_url);
}); 

Ajax calls are "asynchronous" (that's what the A in Ajax stands for). What that means is that they complete sometime in the future and your other javascript continues running. When they complete, they will call their success handler. As such, the ONLY way you can know when the data has been returned from the Ajax call is by either placing code inside the success handler to operate on the returned data or by calling a function from that success handler and passing it the data.

This is asynchronous programming and you MUST use this model if you program with asynchronous functionality of any kind. You cannot use traditional sequential programming with asynchronous function calls.

jfriend00
  • 580,699
  • 78
  • 809
  • 825