-3

Using this to get a value and set it as a var.

var interval;
// Get interval from DB constants table
$.getJSON("/get_slideshow_interval",
    function(data){
        interval = data;
    }
);

console.log(interval);

If I put that console log in the function(data) then it works, but when its out of the getJSON call it returns undefined...

How can I use it outside?

Lovelock
  • 7,689
  • 19
  • 86
  • 186

3 Answers3

3

Ajax calls are Asynchronous; try this instead:

var interval;
// Get interval from DB constants table
$.getJSON("/get_slideshow_interval",
    function(data){
        interval = data;
        console.log(interval);
    }
);
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

It is because of the asynchronous behaviour of $.getJSON. In your code, console.log(interval) will execute even though the data is not received. But if you wrote anything inside function(data){} inside the getJSON function, it will execute only after completing the call.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

You are making an asynchronous call. That means when you try to log the interval value, it actually hasn't been set yet. So you must wait until you can access that variable. Your best approach is to just drop your code in the callback like you had.

You'll probably want it to look like this:

// Get interval from DB constants table
$.getJSON("/get_slideshow_interval",
    function(interval){
        startSlideShow(interval); // Start the slideshow here.
    }
);
Jim Buck
  • 2,383
  • 23
  • 42