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?

3
  • 1
    try declaring var base_url above $.getJSON Commented Oct 23, 2013 at 3:18
  • Hey michael posted an answer Commented Oct 23, 2013 at 3:25
  • possible duplicate of How to return the response from an AJAX call? Commented Oct 23, 2013 at 3:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

How would I access base_url in other parts of my script then?
@MichaelGrigsby - please read what I have added to my answer. You have to program for asynchronous code. You can't use traditional synchronous programming.
So pretty much include everything that uses base_url inside of my callback?
@MichaelGrigsby - yes include it there or call it from there.
You should probably remove base_url = data.base; from the answer code, or comment it out.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.