Sam
Sam

Reputation: 45

How to set global variables in jQuery/JavaScript?

I have an ajax function:

    $.ajax({
        url: 'http://localhost/process.php',
        type: 'post',
        data: '',
        success: function(output) {

var animal = output

        }
    });

I would like the var animal to be set globally so I can call it anywhere on the page even outside the ajax function's success callback. How to do this?

Upvotes: 1

Views: 11766

Answers (4)

silver
silver

Reputation: 630

IF you want to do it dynamically.

jQuery.globalEval()

http://api.jquery.com/jQuery.globalEval/

This method behaves differently from using a normal JavaScript eval() in that it's executed within the global context (which is important for loading external scripts dynamically).

$.globalEval( 'var animal = ' + output );

Upvotes: 0

Pekka
Pekka

Reputation: 449783

Remove the var to make the variable global.

Note however that working with globals is generally viewed as bad practice, because they are very hard to debug.

Upvotes: -1

wmorrell
wmorrell

Reputation: 5337

If you want it to be a global variable, then declare it as a global variable. Generally you do this by putting

var animal;

around the top of your .js file. Then any reference to animal inside your code will be the global variable, unless you re-use the name somewhere else in the scope.

Upvotes: 2

hunter
hunter

Reputation: 63562

Declare it outside of any function or jQuery construct

var animal = null;

$(function(){
    $.ajax({
        url: 'http://localhost/process.php',
        type: 'post',
        data: '',
        success: function(output) {
            animal = output
        }
    });
});

Upvotes: 5

Related Questions