I want to make an AJAX request "in the background" of my JavasSript function, but my script waits for the AJAX request to plete before it continues to execute my code.
$('div').hide();
$.get('/controller/action', { id: 'abc123' },
function(data){
//request pleted
//now update the div with the new data
$('div').html(data);
}
);
$('div').slideDown('slow');
//by now hopefully the div has been updated
//and the user hasn't waited too long
The problem is that the slideDown
animation waits to execute until the request has returned a response. How can I get the the animation to execute at the same time as the ajax request?
I want to make an AJAX request "in the background" of my JavasSript function, but my script waits for the AJAX request to plete before it continues to execute my code.
$('div').hide();
$.get('/controller/action', { id: 'abc123' },
function(data){
//request pleted
//now update the div with the new data
$('div').html(data);
}
);
$('div').slideDown('slow');
//by now hopefully the div has been updated
//and the user hasn't waited too long
The problem is that the slideDown
animation waits to execute until the request has returned a response. How can I get the the animation to execute at the same time as the ajax request?
- Hmm. Where is the code that you want to execute? It is inside the "Request pleted" function? Or is it after $('div').slideDown('slow'); ? – DashK Commented Sep 24, 2010 at 0:06
- 1 Your code works... jsfiddle/pgG9J – chriszero Commented Sep 24, 2010 at 9:03
3 Answers
Reset to default 5You code should already be doing the Ajax request "in the background" (asynchronously). The jQuery.get()
method is shorthand for:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
And the jQuery.ajax()
method is async: true
by default.
Put the slideDown()
in the success callback
$('div').hide();
$.get('/controller/action', { id: 'abc123' },
function(data){
alert("Request pleted");
//now update the div with the new data
$('div').slideDown('slow');
}
);
Unless you are providing default config for AJAX with async: false
(doc).
is it possible the the div contains nothing untill the ajax request is plete, and therefore creates the illusion that its waits?
have you tried the good old alert() debugging after the ajax request?