Shamss Zaidan
Shamss Zaidan

Reputation: 635

Calling two functions with select onchange to pass a variable

I use a function createVariable() to create the variable $user_rank to use it in the second function getRank(). I am calling the two functions using a dropdown:

<select name="rank" onchange="createVariable(this.value); getRank();">

createVariable()

function createVariable(user_id) {
    $.ajax({
       type: "GET",
       url: "file1.php",
       data: "user_id=" + user_id,
       success: function(result){
           $("#TargetRank1").html(result);
       }

    });
}

The seconde function (in file1.php) use this variable $user_rank

getRank()

function getRank(){
    $.ajax({
       type: "GET",
       url: "file2.php?user_rank=<?php echo $user_rank; ?>",
       success: function(result){
         $("#TargetRank2").html(result);
       }
    });         
};

Problem

When I use the dropdown for the first time and I choose the user1, I get only the info from the function createVariable(). When I use it again and choose the user2, the function createVariable() returns the info of the user2 (Good), but the function getRank() returns the info of user1.

Can anyone help me with this?

Upvotes: 0

Views: 213

Answers (1)

Vegeta
Vegeta

Reputation: 1317

May be due to the createVariable() ajax call is not completed before the getRank() function is called. So getRank() gets old data. try using async false

function createVariable(user_id) {
$.ajax({
   type: "GET",
   url: "file1.php",
   async: false,
   data: "user_id=" + user_id,
   success: function(result){
       $("#TargetRank1").html(result);
   }

});

}

Upvotes: 2

Related Questions