8

I need to make this data variable global:

$.ajax({
    url: "get_data.php",
    cache: false,
    dataType: 'json',
    data: {},
    success: function(data) {
        for(var i = 0; i < data.results.length; i++) {
            if(my_data.hasOwnProperty(data.results[i].id)) {
                my_data[data.results[i].id].name = data.results[i].name;
            }
        }
    });

I want to have this globally declared. Do I need to declare it as array?

2 Answers 2

31

Any variable can be "made global" by attaching it as a property of the window.

window.data = data;

You can now access data as a global variable.

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

5 Comments

Also useful is self in case you don't have access to the DOM, such as from a Web Worker.
And where do I put that? outside the ajax scope? I tried that but It says that data is not defined
Put it wherever the original data variable is.
can you please give me an example on my posted question. As I have tried and it is not working. I want to use this data variable as in global scope. Please help
Inside the success function, since that's where data is defined.
0

Set a variable equal to what you wish data to be equal to. And when giving data its value, reference the variable. Like this:

var obj = {};

$.ajax({
    // ....

    data: obj,

    // ....
});

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.