0

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?

3
  • Are you sure accessKey is not the literal string "undefined"? Commented Sep 12, 2013 at 19:35
  • 3
    @abc123 typeof always returns a String. Commented Sep 12, 2013 at 19:36
  • Can you log accessKey to double check its value? It may not be returning what you think. Commented Sep 12, 2013 at 19:36

2 Answers 2

4

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

2 Comments

Looks like I'll have to go with the cookies. I'm trying to store an access token as a cookie for later use with the youtube api. Having some issues tho. Access token returns in the URL, and I need to store it for later. Slowly , day by day, chipping away at this problem.
Feel free to ask one or more separate questions about cookie-specific issues. Just one advice: I'm not a security freak, but maybe you shouldn't store the access token directly in a cookie. Instead, you can store it in a server-side database, and store the correspondent id from the database into the cookie. This way the token is less likely to be exposed. Maybe that's a good question to ask on this site, by the way...
0

Save the value in hiddenfields or in cookie.

1 Comment

Saving a javascript variable in hidden fields is generally not best practice when it comes to persisting variables. As in bfavaretto's answer, there are better alternatives.

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.