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.
It is because the you are not waiting for ajax response to complete. When you click first time the ajax call is made through
postand by second click the response is most likely available so you get it. You can see this putting alert inside the success handler.