Harrison Harrison - 5 months ago 8
Ajax Question

jQuery code after ajax runs before ajax is completed

$("form#go").submit(function(){
var $this = $(this);
var btn = $this.find("button");
btn.text("Searching").attr('disabled','disabled');
$.ajax({
url:
type:
data:
dataType:
success:function(result){
//code....
}
});
btn.text("Go").removeAttr('disabled');

return false;
});


This is my code structure. The problem is
btn.text("Go!").removeAttr('disabled');
runs immediately and I can't see the disabled button and the change of button text , although the ajax part takes 500ms to finish.

If I change the last part to

setTimeout(function () {
btn.text("Go").removeAttr('disabled');
}, 1000);


Then I can see the change for 1 second, so I guess my code works. But I have no idea why it runs before the
ajax
call.

Answer

Call it in ajax success call back, as ajax call is async so your code will get executed before ajax call completes:

$.ajax({

............
...........
success: function()
{
setTimeout(function () {
     btn.text("Go").removeAttr('disabled');
 }, 1000);
}

});
Comments