qinHaiXiang
qinHaiXiang

Reputation: 6419

How to control the code execute order when using ajax to get and assign data in jquery?

these are part of my code :

my problem is the userName assign expression was execute before the function getUserInfomation(userId) , even thought I put the getUserInfomation() in front of them.

global variable:

userInformation = {};

function with event called to assign values:

function assignValues(){
   getUserInfomation(userId);

       userName =  userInformation['user_name'];  // undefined
       userNickName= userInformation['user_nickname'];// undefined

}

function to get data from database via AJAX:

function getUserInfomation (userId){


            $.ajax({
              url: 'include/user.login.process.php',
              data:({userId: userId }),
              success: function(data) {

                if(data){
                    JSON.parse(data, function (key, value) {
                        userInformation[key] = value;
                        console.log(key +' value is '+obj.userInformation[key]);
                    });
                }
             }
           });

        }

thank you very much!!

Upvotes: 0

Views: 180

Answers (2)

Egor4eg
Egor4eg

Reputation: 2708

$.ajax method is asynchronous. It you have to change to place all code which have to be executed after ajax request into callback function: So, you have to use a code like this:

function getUserInfomation (userId){
        $.ajax({
          url: 'include/user.login.process.php',
          data:({userId: userId }),
          success: function(data) {

            if(data){
                JSON.parse(data, function (key, value) {
                    userInformation[key] = value;
                    console.log(key +' value is '+obj.userInformation[key]);

                    assignValues();
                });
            }
         }
       });

    }

Also, you can just call ajax function synchronously. But is a bad practice because you will lose ajax advantages.

        $.ajax({
          url: 'include/user.login.process.php',
          data:({userId: userId }),
          async:false,
          success: function(data) {
          ...

Upvotes: 1

Jaime
Jaime

Reputation: 6814

You need to do your assignment operations inside the success function of the .ajax call

The $.ajax is an asynchronous operation so when you call it, it returns immediately executing the next line of your code (in this case userName = ....), but you haven't got the data back from the server yet, that's what the success callback is for.

Upvotes: 1

Related Questions