1
function json (url){
       $.getJSON(url, function(data) {
           return data;
       })
   }

this function don't see "data"

function MakeAlert(){
       data = json('action.php');
       window.alert(data.name);
}

this work:

  function json (url){
           $.getJSON(url, function(data) {
               window.alert(data.name);
           })
  }

2 Answers 2

2

That's because the $.getJSON is asynchronous. It sends the request and returns immediately. Once the server responds (which might be a few seconds later) it invokes the success callback and that's why the data is accessible only inside this callback.

If you want to block the caller you could send a synchronous request (note that this might freeze the UI while the request is executing which defeats the whole purpose of AJAX):

function json(url) {
    var result = null;
    $.ajax({
        url: url,
        async: false,
        dataType: 'json',
        success: function(data) {
            result = data;
        }
    });
    return result;
}
Sign up to request clarification or add additional context in comments.

Comments

1
function json (url){
   $.getJSON(url, function(data) {
       return data;
   })
}

You cannot use return here. You would return data the to anonymous closure function.

Your best shot is to use a callback function which should be applied when the getJSON success handler is executed.

function json (url, cb){
   $.getJSON(url, function(data) {
       cb.apply(null, [data]);
   })
}

usage

json('action.php', function(data){
    alert(data);
});

Comments

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.