1

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?

2
  • 3
    Keep in mind that your $.ajax call is asynchronous. I can sense a "why is animal undefined?" around the corner. ;o) Commented Feb 4, 2011 at 21:28
  • console.log(typeof animal); //possibly returns undefined due to uninitialized. Commented Feb 6, 2014 at 7:58

4 Answers 4

5

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
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

1 Comment

Is there something wrong with my answer? Why would you down vote it?
-1

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.

1 Comment

IE doenst always define those variables so you can get some error's in IE

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.