Mahmoud K
Mahmoud K

Reputation: 85

How I handle returned data from $.ajax()?

I am trying to configure returned data from $.ajax() by jQuery...

My example is like that:

First of all I'm using codeigniter framework (just for attention)

Now by ajax I am calling function which returned group of divs

exp:

function my_function() {
    for($i = 0; $i < 3; $i++) {
        print '<div class="block">'.$i.'</div>';
    }
} 

Now by js code:

$.ajax({
    type: "POST",
    url: "path/to/my_function",

    success: function(data){
        $('#div#container').html(data);
    }
});

Now all div (3 divs with block class) are appear at one time.(And I don't like that)

I want each one of the last three div appear sequentially (with slideDown for example) Now my specifically question is: How I configure data returned by ajax by loop for example????? to use slideDown for each div??

Upvotes: 0

Views: 150

Answers (2)

dku.rajkumar
dku.rajkumar

Reputation: 18568

add the display:none; initially

function my_function() {
    for($i = 0; $i < 3; $i++) {
        print '<div class="block" style="display:none;">'.$i.'</div>';
    }
} 

then

$.ajax({
    type: "POST",
    url: "path/to/my_function",

    success: function(data){
        $('div#container').html(data);
           $('div.block').each(function(){
             $(this).slideDown(1000);
         });
    }
});

Upvotes: 2

Scott Harwell
Scott Harwell

Reputation: 7465

You fire the slide down function for each div once the other has completed if you want one div to display after the other. You could build a recursive function so you can dynamically set indexes to start and end at certain values. Of course, your div ids will have to be named properly so you can do something like this.

function doSlideDown(startIndex, endIndex){
    $('div#container'+startIndex).slideDown(500, function(){
        if(startIndex < endIndex){
            doSlideDown(startIndex+1, endIndex);
        }
    });
}

$.ajax({
type: "POST",
url: "path/to/my_function",

success: function(data){
    $('div#container1').html(data);
    $('div#container2').html(data);
    $('div#container3').html(data);

    doSlideDown(1,3);
}
});

This will make sure that only one div slides out at a time.

Upvotes: 0

Related Questions