Search code examples
javascriptjqueryajaxpostgresqlresponse

Assign the ajax response to a global variable


In this code, I would want my "userid" from postgresql, which will be the "response" of ajax or variable "res", to be stored in a global variable "id" so I can use it into future use.

var id;

function addUser()
{
  $.ajax({
      url: siteloc + scriptloc + "adduser.py",
      data: {username:$("#login").val(), password:$("#password").val(), email:$("#email").val()},
      dataType: 'json',
      success: function (res) { 
                window.id = res;
                console.log(id);          
            }
    });
}

It all goes well in the console.log(id), showing the id in the console. But when I proceed to the next function,

function setpersonalinfo()
{
  $.ajax({
      url: siteloc + scriptloc + "setpersonalinfo.py",
      data: {userID:id, 
            fullname:$("#fullname").val(),
            birthday:$("#birthday").val(),
            gender:$("#gender").val() }, 
      dataType: 'json',
      success: function (res) {
                  console.log("Successfully added.");
              }
    });
}

The id in "userID:id" is not recognized. How do I do this?


Solution

  • Asynchronously: Inside the addUser()'s ajax success function, call setpersonalinfo() which makes sure that the window.id is already set and ready to use.

    Single-ajax: A better way to do this is to simply call setpersonalinfo() and let the server determine if the user exists already, or if no id value is submitted then assume that a new user would have to be created first. Proper input validation would have to detect duplicate user credential anyway, so that's not unnecessary work. setpersonalinfo() would then return a user id and you could set global variables at that time. Or ideally, instead of using globals, you would use closure to protect the value of the user id from being reset using the javascript console.

    Synchronous: Just use the "asysc": false property when calling addUser() so that setpersonalinfo() is not called until the user id property is set.