0

My need is to set a global variable after a ajax call. The global variable depends on the ajax's success data and I want to access the global variable in some other function.

The global variable should get cleared on a certain click event. If the ajax call made once again I want to set the global variable with a new value.

I tried with declaring var outside the function like var globalvariable and set the global variable value after ajax call like:

window.globalvariable = data;

but I am getting only empty results.

What is the proper way to achieve this?

Jonast92
  • 4,964
  • 1
  • 18
  • 32
rajapallavan
  • 101
  • 1
  • 7
  • 1
    can you please post some code. – A.T. Oct 13 '14 at 07:44
  • The chances are great that trying to set a global variable from the result of an ajax call and then use that global variable in another function is a wrong and misguided way to solve your problem. it is simply not a reliable way to handle asynchronous results. You should read [this post](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) to begin to understand how to properly handle asynchronous responses. – jfriend00 Oct 13 '14 at 08:12

2 Answers2

1

You don't need to access the global variable like window.globalvariable, just globalvariable is sufficient.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
Nishad K Ahamed
  • 1,374
  • 15
  • 25
  • if used in a callback, that looks like a bug; window.globalVariable is more readable – dandavis Oct 13 '14 at 07:57
  • I tried that too but It didn't work. Now I got it working by clearing all sessions and cookies. And is there a way to unset the javascript variable and set with new value. – rajapallavan Oct 13 '14 at 08:06
  • @rajapallavan You can simply give it a new value, or assign it a null if you don't want it to contain anything anymore. – Jonast92 Oct 13 '14 at 09:14
0

you can check whether the variable is assigned or not:

if(typeof globalvariable == 'undefined')
 // variable is not assigned
else 
 // use value of that variable.

if you define variable using 'var' keyword inside a function then it is treated as local variable.

But if you declare variable with out 'var' keyword then it is treated as global variable.

As ajax is asynchronsus most of the time, you should check variable only in callbacks not in functions where you fire ajax.

A.T.
  • 24,694
  • 8
  • 47
  • 65