2
$(document).ready(function() {
          $.ajax({
              url: 'objects.php',
              type:'GET',
              dataType: 'json',
              success: function(response)
               var variable = [some_array];

      //how to create an variable containing json array and access this variable outside?
                }
           });
      }); alert(variable);

Why this does not work? I smell some scope issue...

Thank you.

Michal S
  • 21
  • 2
  • 2
    Ajax is asynchronous. Use the variable in the callback or in a function called by the callback. – Denys Séguret Mar 23 '13 at 11:40
  • As dystroy already stated, the code after the ajax call (alert in your case) is executed immediately, while success is called only after it is being answered. Thus you would not be able to use those variables outside of success. A workaround would be for example to define a global function that takes your variable as an argument which would be called from within success. – Appleshell Mar 23 '13 at 11:46

1 Answers1

0

First off, let me say that changing a global variable inside a callback is not the way to go. You should instead fire all side-effects from within the callback. You'll find your code is a lot easier to reason about and debug if you avoid callbacks affecting each other through global state.

That said, if you want two functions to "share" a variable, just declare it outside where both can see it.

var x = 0; // Declaring this in an outer scope makes f1 and f2 share it.

function f1() {
    x = 1
}

function f2() {
    console.log(x)
}

f1();
f2(); // Prints '1'

The feature responsible for this behavior is closures.

Community
  • 1
  • 1
salezica
  • 74,081
  • 25
  • 105
  • 166