views:

84

answers:

4

I want to make an AJAX request "in the background" of my JavasSript function, but my script waits for the AJAX request to complete before it continues to execute my code.

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        //request completed
        //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?

+2  A: 

You 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.

Daniel Vassallo
The problem is that the animation waits to execute until after the request has returned a response.
Andrew
@Andrew: That's strange. Can you try using `$.ajax` instead of `$.get` and set `async: true`?
Daniel Vassallo
+1  A: 

Put the slideDown() in the success callback

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        alert("Request completed");
        //now update the div with the new data
        $('div').slideDown('slow');
    }
);

Unless you are providing default config for AJAX with async: false (doc).

alex
The problem is that the animation waits to execute until after the request has returned a response. By putting the animation in the callback, it will surely wait until the request has completed. I am trying to make the request and run the animation at the same time.
Andrew
A: 

is it possible the the div contains nothing untill the ajax request is complete, and therefore creates the illusion that its waits?

have you tried the good old alert() debugging after the ajax request?

Patrick
yes, the alert displays, then after clicking ok on the alert, the animation continues.
Andrew
so probably the ajax request is not blocking the animation but instead, until the ajax request is complete, the animation is just not visible due to the lack of content in the div?
Patrick
A: 

It's strange that even async ajax request is blocking the animation. I guess an alternative solution to your problem can be achieved with the pub/sub model using bind and trigger functionality of jQuery. You need to add a listener(bind) to the required div element and then trigger that listener when the ajax response is received.

The code (not tested) should be:

$('div').hide();

$('div').bind('myCustomEvent', function(event, data){
      $('div').html(data);
});

$('div').slideDown('slow');

$.get('/controller/action', { id: 'abc123' },
    function(data){
        $('div').trigger('myCustomEvent', [data]);
    }
);

Hope that helps.

skimnetster