EHerman
EHerman

Reputation: 1892

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax request is run...If it is not I want the user to be redirected to a separate page where the variable is set.

for example I want something like this:

    // if variable is undefined
    if (typeof accessKey === 'undefined') {
        alert('the variable is not set!');
    } else {
            var accessKey = 'some random string generated from google';
                    alert('the variable is set!');
                    proceed to refresh the page and run through check again.
    }

So the first time the page is run, it checks if the variable is set. If the variable is not set it will set the variable and then reload the page and run through the check again.

Problem is 'accessKey' always returns undefined but the code runs through as if the variable is defined. Why?

Upvotes: 0

Views: 136

Answers (2)

bfavaretto
bfavaretto

Reputation: 71918

If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again

There is your problem: variables (or any other piece of js code) do not persist between page reloads.

If you need stuff to persist, you have to use one of these:

  • Server-side sessions or databases (using ajax to pass data to the server and persist it there)
  • Client-side storage (such as localStorage).
  • Cookies (can be generated at client-side or server-side)

Upvotes: 4

sudhansu63
sudhansu63

Reputation: 6180

Save the value in hiddenfields or in cookie.

Upvotes: 0

Related Questions