Spikes
Spikes

Reputation: 176

Changing global variable value not working in javascript

i am having a problem in changing the value of my global variables in javascript...Here's the full code.

//Initialize cordoba
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady(){
    var undefined;
    var phone_number;

    //change phone_number
    checkData();

    //alert the new phone_number
    alert(phone_number);


    function checkData(){
        var db = window.openDatabase("Demo", "1.0", "Demo", 512000);
        db.transaction(selectProfile,DBerror);
    }

    function selectProfile(db){
        db.executeSql('SELECT phone_number FROM profile', [],
            function(db,results){
                if(results.rows.length > 0){
                    //change the global variable(phone_number)
                    phone_number = results.rows.item(0).phone_number;
                }else{location.href = 'index.html';}
            },
            DBerror
        );
    }
}

In every page, i need to get the phone number value from the database, change the global variable (phone_number) to that value and use it through out the whole script. Thanks

Upvotes: 1

Views: 3562

Answers (1)

eidsonator
eidsonator

Reputation: 1325

Declare phone_number outside of any function should work.

You can also use window.phone_number to guarantee a global scope. But this is considered bad practice? I'm sure someone with much more experience than I can explain why.

Upvotes: 1

Related Questions