Ren Tao
Ren Tao

Reputation: 407

Getting Globally declared variable value from 1 function to another function

I have a very common question about javascript i have a globally declared variable but how can a function with that variable pass the value in the globally declared variable then use it in the second function??

 var ID;

    function test() {

       $.getJSON('/Test1/GetTestID', function (test) {
                $.each(test, function () {
         ID = this["ID"]
         alert(ID);
    }
    })
    }

    function test1() {
             $.getJSON("/TestSite?Test=" + ID; )
    }

    alert(ID);
    test();
    test1();

Function test alert the ID but when i declare it Globally it was undeclared.

Can someone help me with this??

Thanks

Upvotes: 0

Views: 41

Answers (3)

Preet
Preet

Reputation: 82

Try this first you set you id to Zero

    var ID =0;

Upvotes: 0

user180100
user180100

Reputation:

Because getJSON is asynchronous, the proper way do perform what you need is to use the returned ID in the callback of getJSON:

function test() {    
    $.getJSON('/Test1/GetTestID', function (test) {
        $.each(test, function () {
            var theId = this["ID"];
            alert(theId);
            test1(theId);
        }
    });
}

function test1(id) {
    $.getJSON("/TestSite?Test=" + id);
}

test();

Upvotes: 0

Rob M.
Rob M.

Reputation: 36511

I think you are expecting getJSON to be synchronous, but it is not. If the calls are dependent you should nest them:

function test() {
       $.getJSON('/Test1/GetTestID', function (test) {
           $.each(test, function () {
              ID = this["ID"]
              $.getJSON("/TestSite?Test=" + ID; )
           })
       })
}

test1 is being called before test has completed its getJSON call

Upvotes: 1

Related Questions