3

I have the following source code:

var labeled_pic = new Array();
var testing;
function get_label_pic(){
    $.ajax({
        url: "localhost/advanceSearch/index/getlabelpic",
        type: "POST",
        dataType: "json",
        success: function(data) {
            $.each(data, function(key, data){
                labeled_pic[key] = data;
            });
            testing = "testing";
        }
    });
};
get_label_pic();
console.log(labeled_pic);

And then I call those function using get_label_pic();, after that I want to access labeled_pic array using labeled_pic[3] but it's return undefined. I use firebug, and I try to write this console.log(labeled_pic), and it's return: Firebug result How can I access the labeled_pic variable,.?

7
  • when are you accessing labeled_pic variable? it will be filled with values after response comes from server - after your success function executes. Commented Dec 15, 2011 at 9:27
  • its because of the asychronous behavior of $.ajax Commented Dec 15, 2011 at 9:27
  • put the console.log statement after testing = "testing"; It should work as expected Commented Dec 15, 2011 at 9:28
  • @Zango I'll access it in img tag,. Commented Dec 15, 2011 at 9:30
  • @Zango this is when I use the variable: $("#result").append("<img src='" + labeled_pic[3] +"' />"); Commented Dec 15, 2011 at 9:32

5 Answers 5

2

The problem is that you are making an asynchronous call (the AJAX request) so your JavaScript continues and doesn't wait for the call to come back.

So the call to get_label_pic() will take no time at all and your code will continue straight to the console.log(labeled_pic) (which won't be set yet, because the success callback in your AJAX call won't have finished.

If you want to us it, then you'll need to put your code into your AJAX success, or call another function from it:

function get_label_pic(){
    $.ajax({
        url: "localhost/advanceSearch/index/getlabelpic",
        type: "POST",
        dataType: "json",
        success: function(data) {
            $.each(data, function(key, data){
                labeled_pic[key] = data;
            });
            testing = "testing";

            console.log(labeled_pic); // this will show the values
            callmyOtherFunction(); // To call something else
        }
    });
};
get_label_pic();
console.log(labeled_pic); // This will be undefined

What actually happens is this:

  1. Creates the function get_label_pic
  2. Calls get_label_pic()
    1. Makes the ajax request
  3. Calls console.log
  4. Script is at the end
  5. Some time passes, then the server response comes back
    1. Iterates through the data, setting labeled_pic[key]
    2. Sets testing = 'testing'
    3. Calls console.log(labeled_pic);
    4. Calls callmyOtherFunction()
Sign up to request clarification or add additional context in comments.

Comments

1

As your ajax call is asynchronous, there is a great chance that you will try to read the array, before the ajax-call is completed. If you you create a callback-function to be triggered when the ajax-call is complete, and put your code within that callback, then you are sure that the ajax-call is complete, before you are trying to access the array.

function get_label_pic(){
    $.ajax({
        url: "localhost/advanceSearch/index/getlabelpic",
        type: "POST",
        dataType: "json",
        success: function(data) {
            $.each(data, function(key, data){
                labeled_pic[key] = data;
            });
            testing = "testing";
        },
        complete: doWhatYouWantToDo()
    });
};

function doWhatYouWantToDo()
{
   alert(labled_pic[3]); // <!-- now the array is populated
}

4 Comments

is this function below will work,.? function doWhatYouWantToDo() { labeled_pic[3] = "stat.png"; }
@Praditha With that function, you would replace what was stored in labled_pic[3] by the ajax-call with stat.png. Is that what you want to accomplish?
ya, but I still can't store ajax result to labeled_pic where the labeled_pic is global variable,.
@Praditha I'm afraid I don't understand how you mean. Since you declare var labeled_pic = new Array(); outside both get_label_pic and doWhatYouWantToDo, the variable is accessible within both functions. What are you trying to do?
0

The function is a closure and hence labeled pic has fallen out of scope.

If you pass it as a parameter to your callback function it will be encapsulated in the closure and available at the time the callback is executed .

HTH

5 Comments

may you give me an example please,.:)
This isn't a scope problem. labeled_pic is a global variable and will be in scope inside the callback. The problem is that the code that assigns a value to it is executed after the console.log because it's asynchronous.
I don't think this is the problem. labeled_pic is a global variable, no?
Anyway, without seeing the whole javascript, how can we know the variable is global as it was declared with var. Maybe this piece of code is encapsulated within another function.
@DidierG. - True, we don't know that it's global, but it's certainly in scope inside the callback, whether it's global or not. If the code in the question is a snippet from inside a larger function, the variable won't be global but it will still be accessible from inner functions.
0

You have to call console.log(labeled_pic); inside the success callback of the $.ajax

...
 success: function(data) {
            $.each(data, function(key, data){
                labeled_pic[key] = data;
            });
            testing = "testing";
            //here call the console.log
        }
...

Comments

0

you must execute that code at the end of success function, so your code must look like this:

var labeled_pic = new Array();
var testing;
function get_label_pic(){
    $.ajax({
        url: "localhost/advanceSearch/index/getlabelpic",
        type: "POST",
        dataType: "json",
        success: function(data) {
            $.each(data, function(key, data){
                labeled_pic[key] = data;
            });
            testing = "testing";

        $("#result").append("<img src='" + labeled_pic[3] +"' />");

    }
});

}; get_label_pic();

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.