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();
}
});
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();
}
);
You need to wait for your post to finish and send a success message back (via JSON), then do the refresh action.
you can add call back function to your post
$.post( "includes/shoutBoxPost.php",{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()})
.done(function( data ) {
$("#messageBox").val("");
$("#shoutRefresh").click();
});