Frank
Frank

Reputation: 1864

jQuery $.post() request doesn't work unless ran twice

Here are two functions.

function getUserInformation(UserID) {
    $.post("assets/scripts/chat/get_user_info.php", {
        UserID: UserID
    }, function (data) {
        if (data == "error") {
            alertBar('negative', 'There was an error sending the message');
        }
        window.username = data;
    })
}

function CreateChatBox(UserID) {
    if ($('#' + UserID).length == 0) {
        getUserInformation(UserID);
        alert(username);
    }

My issue is, that when the CreateChatBox() function is executed, it has to be clicked twice in order for it to actually work. How ever if I remove the getUserInformation() function from the CreateChatBox() function the CreateChatBox() function executes successfully.

Could anybody help me with this issue? Thanks.

---Edit (extra Detail)----

When I click a link <a onclick = "CreateChatBox()">Some link</a> nothing happens. But when I click it the second time it does work. If I remove the function getUserInformation() from the CreateChatBox() function the CreateChatBox() function works first time when the link is clicked.

Upvotes: 0

Views: 472

Answers (2)

dfsq
dfsq

Reputation: 193281

This is AJAX which means request is asynchronous. What you should do is to pass callback function as the second argument of your getUserInformation which will be invoked when data is available:

function getUserInformation(UserID, callback) {
    $.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data) {
        if (data == "error") {
            alertBar('negative', 'There was an error sending the message');
        }
        callback(data);
    })
}


function CreateChatBox(UserID) {
    if ($('#'+UserID).length == 0) {
        getUserInformation(UserID, function(username) {
            alert(username);
        });
    }
}

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

It is because the you are not waiting for ajax response to complete. When you click first time the ajax call is made through post and by second click the response is most likely available so you get it. You can see this putting alert inside the success handler.

function getUserInformation(UserID) {
   $.post("assets/scripts/chat/get_user_info.php", 
   {
         UserID: UserID
   }, 
   function(data){
         if (data == "error") {
             alertBar('negative','There was an error sending the message');
         }
         window.username = data;
         alert(window.username);
   });
}


function CreateChatBox(UserID) {
   if ($('#'+UserID).length==0) {
        getUserInformation(UserID);
   }
   //alert(username);
}

Upvotes: 3

Related Questions