0

Code explains all:

//
// … code ...
//
$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        var my_data = data;
    }
});
//
// … code ...
//
console.log(my_data); // NOT in scope

How do I get access to my_data outside of the AJAX call? I've read that maybe a closure is needed? I can't find any examples that do want I want though.

Many thanks.

5 Answers 5

2

Ajax is async call and success may be fired after console.log, you can call a function from success and pass data to it.

$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        yourFun(data);
    }
});

function yourFun(data)
{
}

To giving function instead of success.

$.ajax({
    dataType: "json",
    url: "foo",
    success: yourFun
});

function yourFun(data)
{
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it could be but for clarity of code we can define a function and call it.
Thumbs up :) In this particular case it looks clearer to me. But that's just my personal opinion.
1

Generally speaking, you don't. AJAX calls are asynchronous so there's no guarantee of a value immediately after the jQuery.ajax() function has executed; you need to wait until the AJAX call has completed, and the success callback has executed, before you attempt to use that variable.

The easiest approach is to just use that value inside the success callback. If you really need it to be available outside then make it a variable that's visible to all of your code (not necessarily global, depending on how your code is structured), and check that it has a value before you attempt to use it in any other functions.

Comments

0

Define my_data as global as below,

var my_data;

$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        my_data = data;
    }
});
//
// … code ...
//
console.log(my_data); // NOT in scope

Comments

0

Declare my_data variable globally..

var my_data = data;

    $.ajax({
        dataType: "json",
        url: "foo",
        success: function(data) {
            my_data = data;
        }
    });

Comments

0

Use my_data as gloabl variable to access data outside of ajax.

var my_data = '';
$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        my_data = data;
    }
});

console.log(my_data);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.