Tom S Tom S - 7 months ago 20
Javascript Question

jquery click happens too fast to refresh results from database?

I'm making a simple shoutbox and when someone posts a message the message is added to the database just fine. I made a refresh button which populates all the messages in the text area.
I am trying to call the .click() on the refresh button after the person enters the message but I think it happens too fast and doesn't catch the new message in the database. I works if I add an alert to give it more time. Is there a better way?

$("#shoutBtn").click(function(event){
event.preventDefault();
$.post("includes/shoutBoxPost.php", {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()});
$("#messageBox").val("");
$("#shoutRefresh").click();
});


I changed my code to the long hand ajax way and it works thanks for answers folks

$.ajax({
type: 'POST',
data: {"message": $("#messageBox").val(),
"name": $("#userNameWelcome").html()},
url : 'includes/shoutBoxPost.php',
success : function(data) {
$("#messageBox").val("");
$("#shoutRefresh").click();
}
});

Answer

See the documentation for jQuery .post. You can define a success callback that will only fire once the post request successfully returns.

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

$.post("includes/shoutBoxPost.php", 
    {"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()},
    function( data, textStatus, jqXHR ) {
        $("#shoutRefresh").click();
    }
);
Comments