0

I'm trying to store data from a xml-file in a associative Array. Creating the array works fine but I can't access the data in other functions (i.e. checkArray()).

var picSetsData = (function () {
    var _picSets = [];

    $.ajax({
        type: "GET",
        url: "xml/content.xml",
        dataType: "xml",
        success: function (xml) {

            $(xml).find('set').each(function (i) {
                _picSets[i] = [];
                _picSets[i].fehler = [];
                _picSets[i].url = $(this).find('src').text();

                $(this).find('spot').each(function (e) {
                    _picSets[i].fehler[e] = [];
                    _picSets[i].fehler[e].x = $(this).find("x").text();
                    _picSets[i].fehler[e].y = $(this).find("y").text();
                });
            });
        }
    });

    return {
        getPicSets: function () {
            if (_picSets) return _picSets;
            else {
                console.log('error');
            }
        }
    };
})();

checkArray();

function checkArray() {
    console.log(picSetsData.getPicSets().length); // 1
    console.log(picSetsData.getPicSets()); // my Array Data
    console.log(picSetsData.getPicSets()[1]); //undefinded
    console.log(picSetsData.getPicSets()[1].url); //undefinded
}

Any ideas to solve this? Thx.

Pointy
  • 405,095
  • 59
  • 585
  • 614
rttmax
  • 344
  • 1
  • 12

3 Answers3

0

You've declared _picSets as a local variable inside the function picSetsData. You need to declare it outside of the function if you want to make it a global variable that can be shared across functions.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Well he's trying to `return` it from the function that makes the ajax call, but of course that won't work either. – Pointy Apr 04 '12 at 13:30
0

The $.ajax() call is asynchronous, so the surrounding function will return long before the data for the array is sent by the server.

You can do your "checkArray()" work inside the "success" callback.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Your right. I put the checkArray() inside $(document).ready(function(){...}); and erverything works now – rttmax Apr 04 '12 at 13:37
0

There's no associative arrays there, just regular arrays.

Array indexes are zero based, so if you have one item in the array, it's at index zero:

console.log(picSetsData.getPicSets()[0]);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005