bofanda
bofanda

Reputation: 11806

Getting data from JSON file value is 'undefined'

I'm trying get values from JSON file, the data stored in form of array.. Here is the code:

JS:

var initDate = new Date("7/9/2013");
var diffDays = 0;
var timeS;

function taqvimSingleDate() {
    // Calculation of Dates difference
    var currDate = new Date();
    diffDays = Math.floor((currDate.getTime() - initDate.getTime()) / (1000 * 60 * 60 * 24));

    $.getJSON('allData.json', function(data) {
        if (data != '' || data != undefined) {
            var addTohtml = '';
            addTohtml += '<td>' +data[diffDays].date_g+ '</td>';
            $('#singleDate').html(addTohtml);

            // Display appropriate time according to location (01 or 02 etc.)
            switch(getCity) {
            case '01': $('#sahari').html(data[diffDays].sahar_1);
                       timeS = data[diffDays].sahar_1;
                break;
            case '02': $('#sahari').html(data[diffDays].sahar_2);
                       timeS = data[diffDays].sahar_2;
                break;
            case '03': $('#sahari').html(data[diffDays].sahar_3);
                       timeS = data[diffDays].sahar_3;
                break;
            case '04': $('#sahari').html(data[diffDays].sahar_4);
                       timeS = data[diffDays].sahar_4;
                break;
            }
        } else {alert("Database is undefined/empty!");}
    });
}
alert(timeS);

The result of element #sahari is correct displayed (according to the value of getCity), but problem is my timeS variable is undefined and I'm stuck here. How to pass the value of #sahari correctly to timeS variable?

Upvotes: 0

Views: 330

Answers (1)

Amberlamps
Amberlamps

Reputation: 40448

Actually, your value is stored in timeS, but you cannot use it at that point in time. It is only available after your callback went through sucessfully. Call a function that is processing your desired variable within your callback function and you will be able to access timeS.

Upvotes: 1

Related Questions