How can I control the JS executes in order with ajax? Here is my code:
function forexample() {
$(".bewait").css("display", "block");
ajaxrequest(); // here is a ajax request method.
// I also added "async: false" in the method.
$(".bewait").css("display", "none");
}
when I run the forexample()
, it works correctly in Firefox, but I found the chrome did not, it seems chrome runs the ajax method firstly, then runs the css control js together.
How can I fix it to run correctly in chrome?
You should add $(".bewait").css("display", "none");
to the onComplete handler. For example:
$(".bewait").css("display", "block");
$.ajax({
type : 'POST',
url : url,
async : false,
data : postData,
complete : function (){
$(".bewait").css("display", "none");
}
});
Use a callback to ensure the second css statement only executes after a response is recieved:
ajaxrequest({
onResponse : function() {
$(".bewait").css("display", "none");
}
})
You'll probably want to handle errors as well but this should be enough to get started