0

I am sure I am missing something obvious, but whatever it is I can't seem to figure it out.

Here is what I have

var warr = new Array();

$('#step3next').click(function() {
    $.post('AJAX_GetGameWords.asp',function(data) {
        fw(data.warray);
    },"json");

    $('.vardisplay3').append(warr+'');
});

function fw(x) {
    warr = [x]; 
}

Ultimately what I am wanting is to be able to use the warr array anywhere.

If I put the $('.vardisplay3').append(warr+''); just under fw(data.warray); then it works just fine and displays in .vardisplay3, but with where it is now, it doesn't display anything.

I would think since warr is set as global, it would work, but I am obviously missing a scope issue or something.

Can anyone explain what is going on and how can I have the ability to use the warr array anywhere.

Thanks

1
  • 1
    It's not a scoping issue, it's a timing issue -- the $.post callback function doesn't run until at least after the current function call stack is cleared. Commented May 7, 2013 at 16:36

3 Answers 3

3

It's not a scope issue, it's an order of execution issue. .post() is asynchronous, so this line of code:

$('.vardisplay3').append(warr+'');

is being executed before this line of code:

fw(data.warray);

The scope is fine, but if you want something to happen in response to an asynchronous AJAX call (such as appending a returned value) then it needs to be invoked from the call-back function of that AJAX call. Otherwise it'll execute before the AJAX call is finished and it won't have any data to use.

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

Comments

2

post is asynchronous.

you need to use the success callback if you want to use the returned data

http://api.jquery.com/jQuery.post/

Comments

0

You can change the $.post with an ajax call like this it will be callback your data easily and prevent your this issue...

$.ajax({
  type: "POST",
  url: "AJAX_GetGameWords.asp",
  data: "",
  async: false,
  success: function(t){
    alert(t);// You can call your function HERE
  }
});  

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.