Trevor Blackman Trevor Blackman - 6 months ago 11
Javascript Question

Load External JSON once, use it repeatedly....?

When my page loads, I want to immediately pull in JSON data from another server using $.ajax(), and I want to be able to access all the data without having to re-request the json file. The problem is, when I assign the data to a variable, the scope of that variable is confined to the $.ajax() function and I can't access it elsewhere...

It seems like since I have already loaded that information, I should be able to use it as many times as I need too without having to re-request it over and over again (slow). Using simple reddit.json request for example below

$(document).ready(function(){
$.ajax({
type: "GET",
url: 'https://www.reddit.com/.json',
timeout:3000,
dataType: 'JSON',
jsonpCallback: 'callback',
success: function(data) {
console.log(data);
var myData = data; //this variable is confined :(
},
error: function(){
console.log('error');
}
});
});


If I run it outside of the document.ready(), then I can get to it globally, but I didn't know if that was cool or not, or like best practices, you know...

Whats the best way to access an already-loaded json object outside of the scope of the function that made it's initial request? Or is it even possible...?

Answer

You can use any one of the two options given below.

1.Declare a global variable before $(document).ready() function.Then use it inside like below.

<script>
var myData;
$(document).ready(function(){   
 $.ajax({
    type: "GET",
    url: 'https://www.reddit.com/.json',
    timeout:3000,
    dataType: 'JSON',
    jsonpCallback: 'callback',
    success: function(data) {
        console.log(data);
        myData = data;  //this variable is confined :(
    },
    error: function(){
        console.log('error');
    }
});
});
</script>

2.Place your data in HTML5 session storage or local storage depending on your requirement.Like below.

<script>
$(document).ready(function(){   
 $.ajax({
    type: "GET",
    url: 'https://www.reddit.com/.json',
    timeout:3000,
    dataType: 'JSON',
    jsonpCallback: 'callback',
    success: function(data) {
        console.log(data);
        sessionStorage.myData=data;  //setting variable in session storage
        console.log(sessionStorage.myData); // getting variable from ss
        // for local storage replace sessionStorage with localStorage in above two lines
    },
    error: function(){
        console.log('error');
    }
});
});
</script>