2

In my json function, it will return a few value and i want to store it in global variable:

function PrepareJsonFormat() {
    jQuery.getJSON(
    "/abc/xyz", { varA: jQuery("#qwerty").val() },
    function (data) {
        if (data != null && data != "") {
            $.each(data, function (i, val) {
                ==> all the val.value i want to put in global variable
            });    
        }
    });
}

After all the values are been stored in the global variables, i will click a button and use the values. How can i do this?

Please help. Thank you.

6 Answers 6

3

I usually advise against using globals. It is better to have the variable as a return value of your function or have a callback argument which you can call with your value as soon as you are done (for example, in your getJSON callback function):

function PrepareJsonFormat(callback) {
    var myData = {}; // all data will be stored here
    jQuery.getJSON(
    "/abc/xyz", { varA: jQuery("#qwerty").val() },
    function (data) {
        if (data != null && data != "") {
            $.each(data, function (i, val) {
                // put the data in your variable
                myData[i] = val;
            });
            // when we are done, call the callback with myData
            callback(myData);
        }
    });
}

Use like this:

PrepareJsonFormat( function(returnedData) {
    // use returnedData (myData) here
});

The advantage over using globals is that if something calls your function twice, you don't overwrite the global. Also, any other javascript will have access to your global variables, so if somebody else uses the same name (and trust me, they will :) ), your data might get overwritten before you can use it. Also, other scripts might have already declared a global variable with that name (bad practice, but people do it), in this case you might break other scripts on your page.

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

Comments

0

Your solution is as simple as deciding where in your code to declare the variable you write to, and that depends on where this function resides.

If you want something globally accessible to everything else on the document, you may choose something like:

$(function(){
   var global = [];

   function PrepareJsonFormat() {
    jQuery.getJSON(
    "/abc/xyz", { varA: jQuery("#qwerty").val() },
    function (data) {
        if (data != null && data != "") {
            $.each(data, function (i, val) {
                global[i] = val;
            });    
        }
    });
   }
});

I suspect your question maybe touches on the fact you're unsure on the syntax of writing an arbitrary amount of 'entries' to a variable. Declare your variable as an array, use i to specify the element in the array you wish to assign data to, and assign it val.

Comments

0

In Javascript, variables have function scope, meaning that a variable is only visible to anything inside the function that it was also created in.

So basically, you need to declare the variable in the correct scope that you want to use it in, then you can assign a value to it as long as the line assigning the value to it is in the same scope as the variable declaration.

when declaring a variable, you should always use the var keyword, however, if you do not use the var keyword, then the variable is automatically created in global scope (as in the window object scope).

Comments

0

I guess this should do:

function PrepareJsonFormat() {
  window.arr = []; // declare this array var to hold an obj
  jQuery.getJSON(
    "/abc/xyz", {
      varA: jQuery("#qwerty").val()
    },
    function(data) {
      if (data != null && data != "") {
        $.each(data, function(i, val) { 
          arr.push(val.value); // here you can push the val.value in the array decalred.
        });
      }
    });
}

Comments

0

Variables declared inside the <script> tag and outside the function can be accessed by any other function. Just declare that variable outside that function. you can use that variable in both functions.

Comments

-1

Declare variable outside functions

<script>
    // this is a global variable
    var foo = "foo";
</script>

If you have to generate global variables in production declare them explicitly:

window.globalVar = "This is global!";

Also, it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), this generates implicit global variable, which is a bad thing to do and would generate an error in strict mode.

In your case, your code must be like thisw:

var mArray = [];  // declare global array

function PrepareJsonFormat() {
    jQuery.getJSON(
    "/abc/xyz", { varA: jQuery("#qwerty").val() },
    function (data) {
        if (data != null && data != "") {
            $.each(data, function (i, val) {
                  // fill the array
                  mArray[i] = val;  
                  // or
                  mArray.push(val);

            });    
        }
    });
}

2 Comments

how about if i want to store all the variables in array because im not sure how many value will i get from the json function.
declare the array as var mArray = [];

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.