0

Hi I have ajax which calls json, i wanted to have this json object a javascript global reference so that I can use this reference to access json object. here is code.

var jsonData;

$.getJSON(url, function(json) {
 jsonData = json; /*i wanted to pass this json object to global reference*/
});
nextAlbum function(){
    console.log(jsonData.albums.length); /*I have to acces here*/
}

your help will be appreciated. here is my latest code.

var mysplitSlider = (function(){
var init, findTotalAlbums, countAlbum;
var jsonData;

return{
    init: function(url){
        $.getJSON(url, function(json) {
            jsonData = json;
        });
    },
    nextAlbum:function(){
        console.log(jsonData.albums.length);
    },
    previousAlbum:function(){}
};

})();

var url = "assets/images/detail_view_gallery/data.json";

mysplitSlider.init(url);

please help me so that I can access reference variable/object for json.

3
  • isn't this code working as expected, any errors u getting? Commented Oct 5, 2012 at 9:46
  • nextAlbum function() {... is a syntax error. Commented Oct 5, 2012 at 9:48
  • what's the output of this console.log(jsonData.albums.length); Commented Oct 5, 2012 at 9:51

3 Answers 3

1

If I've understood your question correctly, then you're running into problems with the asynchronous nature of getJSON.

Since getJSON is asynchronous your jsonData variable will not contain any data until that asynchronous call has received a response and executed the callback. If you attempt to access jsonData before that's happened, you'll likely run into errors.

You will need to move any code that relies upon jsonData into the callback function.


Note, the above assumes your syntax errors are just a result of creating the question and are not part of your actual code.

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

Comments

1

Modified code: jsonData would not be available immediately since getJSON is a asynchronous call. and your function nextAlbum definition was not currect.

  var jsonData ;
$.getJSON(url, function(json) {
 nextAlbum (json);
 jsonData = json; /*i wanted to pass this json object to global reference*/
});
function nextAlbum (json){
    console.log(json.albums.length); /*I have to acces here*/
}

Comments

0

Remember, AJAX is Asynchronous JavaScript And XML...

function nextAlbum(jsonData){
    console.log(jsonData.albums.length);
    /* If you want, add a global var to save json */
}

$.getJSON(url, nextAlbum);

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.