简体   繁体   中英

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?

Creating an object with the property id like so...

var data = new Object({id: ""});

And then set data.id as the output,

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

and in your other function reference data.id,

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

Sorry about the formatting.

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.

Try this: create a closure that encapsulates your user data handling, then make the returned id a variable within your closure. It's also a good idea to use the following pattern in your js (called 'module').

function Users() {
    //Global vars
    var newUserId;

    var methods = {
        add: function(callback) {
                $.ajax({
                url: siteloc + scriptloc + "adduser.py",
                data: { username: $("#login").val(), password: $("#password").val(), email: $("#email").val() },
                dataType: 'json',
                success: function (res) {
                    newUserId = res;
                    console.log(newUserId);
                    if (typeof(callback) == "function") {
                        callback();
                    }
                }
            });
        },
        updatePersonalInfo: function () {
            $.ajax({
                url: siteloc + scriptloc + "setpersonalinfo.py",
                data: {
                    userID: newUserId,
                    fullname: $("#fullname").val(),
                    birthday: $("#birthday").val(),
                    gender: $("#gender").val()
                },
                dataType: 'json',
                success: function (res) {
                    console.log("Successfully added.");
                }
            });
        }
    };

    return methods;
}

//Usage example. add() could also pass the new user's id to the callback as a parameter, so
//you wouldn't have to store it at all.
var users = new Users();
users.add(function () {
    users.updatePersonalInfo();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM