0

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

6
  • 1
    ID = this["ID"]?? What are you trying to do? Commented Feb 20, 2014 at 6:16
  • @RC. actually the id came from getJson , now added something .. Commented Feb 20, 2014 at 6:20
  • you can't, you have to call test1 in the callback of getJSON Commented Feb 20, 2014 at 6:22
  • @RC. so its impossible to pass value on the globally declared variable and fetch it in another Function?? Commented Feb 20, 2014 at 6:23
  • You forgot the semicolon on ID = this["ID"] Commented Feb 20, 2014 at 6:24

3 Answers 3

1

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

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

Comments

0

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();

4 Comments

sir the function test1(id) or function test1(theId)?
@RenTao some basic tutorial about JS variable scope and function might be a good idea
just clarifying things sir
In test() if theId is 123 then test1(theId) call test1 with the value 123 and in test1 we get 123 as value for id. theId only exists in test() and id only exists in test1.
0

Try this first you set you id to Zero

    var ID =0;

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.