0

I'm having a problem of using variables between functions. As you can see down below User.username is available and good at the sign up page, but when you go to the login page I told it to first alert the value of User.username, and it alerts undefined? I'm confused here. I'm pretty sure I'm missing a concept here. Anyways Thank you so much!:

Here is a plunkr: http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH

Here is my script.js:

app.controller("AuthCtrl", ["$scope", "Auth","$rootScope", 
  function($scope, Auth, $rootScope) {
var User = {}

      $scope.createUser = function(username, email, password) {
        $rootScope.usernames = username
        User.username = username
        $scope.message = null;
        $scope.error = null;
    var ref2 = new Firebase("https://uniquecoders.firebaseio.com/");
  ref2.createUser({
    email: $scope.email,
    password: $scope.password
  }, function(error, userData) {
    if (error) {
      switch (error.code) {
        case "EMAIL_TAKEN":
          alert("The new user account cannot be created because the email is already in use. Try to login");
          break;
        case "INVALID_EMAIL":
          alert("The specified email is not a valid email.");
          break;
        case "INVALID_PASSWORD":
          alert("The Specified Passowrd Is not valid.")
          break;
        default:
          alert("Error creating user:", error);
      }
    } else {
      alert("Successfully created user account with username" + User.username);

      window.location.hash = "/User"
    }
  });


      };

       $scope.logIn = function(){
         alert(User.username)
       $rootScope.usernames = User.username
        $scope.message = null;
        $scope.error = null;
        var ref2 = new Firebase("https://uniquecoders.firebaseio.com/");
        ref2.authWithPassword({
          "email" : $scope.logInemail,
          "password" : $scope.logInemailpassword

        }, function(error, userData){

          if(error){
            alert("Login Failed Because : " + error)
          }
          else{
            alert("Logged In!")
            window.location.hash = "/User"
          }

        })

      }

  /*  $scope.removeUser = function() {
      $scope.message = null;
      $scope.error = null;

      Auth.$removeUser({
        email: $scope.email,
        password: $scope.password
      }).then(function() {
        $scope.message = "User removed";
      }).catch(function(error) {
        $scope.error = error;
      });
    };*/
  }
]);
21
  • 1
    This is why cookies exist. Read about them Commented Jan 10, 2016 at 19:34
  • @Hogan i dont understand cookies. I dont want to go to another topic. Im asking if somone knows a concept? Commented Jan 10, 2016 at 19:35
  • Cookies are the concept. Cookies are how you save data between pages. That is what you are asking about right? Commented Jan 10, 2016 at 19:36
  • Wait im even more confused now @Hogan Commented Jan 10, 2016 at 19:36
  • 3
    As soon as you change the page by setting window.location or when the user clicks on a link that changes pages, then the entire Javascript environment (including all variables) is destroyed and replaced with a new one. No JS variables survive from one page to the next. Cookies and Local Storage are the two client-side places you can store stuff that you can then retrieve from a future page. Commented Jan 10, 2016 at 19:44

2 Answers 2

0

When page reloads the entire javascript is re executed. So user object populated in registration process is no longer available in login function because page has reloaded on clicking on signup button.
So we need to store the user name in cookie so that we can access it any time. Even when its removed from javascript runtime it will be there in the browser cache.
Its risky to store passwords in cookies for security issues.

On successful registration save the username in cookie.
Some thing like this

document.cookie ="username =" +username + "; " +"email ="+ email;

In login function get cookie values and check if email of user is same as entered

function getCookie(name ) {
   var pairs = document.cookie.split("; "),
   count = pairs.length, parts; 
   while ( count-- ) {
    parts = pairs[count].split("=");
    if ( parts[0] === name )
        return parts[1];
}
 return false;
}


var username=getCookie("username");
var email=getCookie("username");
if($scope.logInemail ==email)
  {
     alert(username);
  }
Sign up to request clarification or add additional context in comments.

6 Comments

ReferenceError: getCookie is not defined at Scope.$scope.logIn (preview.c9users.io/amanuel2/fourm/script.js:76:24)
code updated with getCookie function!. You can have that in function global scope. It can be used anywhere for getting cookie value.
I told it to alert the var username and it said it was false. Help please. Code is in script.js
alert("Successfully created user account with username" + User.username); You need to set cookies after this line. By adding the line document.cookie ="username =" +username + "; " +"email ="+ email;
|
0

You have to remember that a web application is a communication between the browser the the web server. The browser and the server can be on different machines (even if they aren't when you are testing.)

There are two ways to make this work

While the browser and the server communicate some information is saved and passed back and forth on both ends -- this is called a cookie. This is the most common way to do save data between pages. The browser requests a page. When it get the reply from the server it contains a cookie. The next time the browser requests a page it includes the cookie in it's request. In this way the server knows the request is related to the prior request.

The server is smart enough to keep track of all "sessions" by different browsers. It then saves session data about that communication -- when it gets the next request from the same browser it goes to the session data and retrieves information about that that browser and what it was doing. (Often this is done with cookies.)

1 Comment

@Dsafds - as I said in my first comment "This is why cookies exist. Read about them".

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.