0

How can I move the variable userID out of its' scope (once it returned from the ajax POST call), because I would need its' value below (in the GET request)? Should I use a callback?

firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) {
console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid)
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
// Send token to your backend via HTTPS (JWT)
$.ajax(
    {
      url: '/auth',
      type: 'POST',
      data: {token: idToken},
      success: function (response){
      var userID = response.userID
      //set database ref, pull out info based on ID
      }})
$.get(
    {
      url: '/members-area/',
      data: {userID: userID}
    })
huzal12
  • 79
  • 2
  • 10
  • The variable *is* in the right scope. What you are trying to do is move a future value to the present, which is not possible. – Bergi May 07 '17 at 16:04
  • @Bergi not really, I am trying to access that variable in the following function that was declared. – huzal12 May 07 '17 at 21:23
  • Ah, right, the variable was local so not in the right scope. But still, the following function call (`$.get`) that tries to access it happens right after the `$.ajax` request was started, without waiting for the response to return. – Bergi May 07 '17 at 21:57

1 Answers1

3

Move get inside ajax success?

$.ajax({
    url: '/auth',
    type: 'POST',
    data: {
        token: idToken
    },
    success: function (response) {
        var userID = response.userID

        $.get({
            url: '/members-area/',
            data: {
                userID: userID
            }
        })
    }
})
Alex
  • 59,571
  • 22
  • 137
  • 126