tags:

views:

7080

answers:

4

Hi..

How do I refresh element (div, class whatever) after another jquery action?

I have this action which is deleting a record from database and I need to refresh div which is fetching some other data from database as well...

Well here's code:

$(function() {
    $(".delete").click(function() {
        var commentContainer = $(this).parent();
        var id = $(this).attr("id");
        var string = 'id='+ id ;

        $.ajax({
           type: "POST",
           url: "delete.php",
           data: string,
           cache: false,
           success: function(){
               commentContainer.slideUp('slow', function() {$(this).remove();});
           }
         });

        return false;
    });
});

Thanks for all help! :)

A: 

Why don't you add a function that do the refreshing after the first ajax is success (assuming that you cannot combine to the two into one ajax requist which a much more efficient).


...
function doRefresh_ofAnotherDiv() {
   $.ajax({
      type: ...,
      url: ...,
      data: ...,
      cache: ...,
      success: function(){
         // updateAnotherDiv();
      }
   });
}
...
$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(){
      commentContainer.slideUp('slow', function() {$(this).remove();});
      doRefresh_ofAnotherDiv();
   }
});
...

Hope this helps.

NawaMan
+4  A: 

During an AJAX call you can use the success function to run commands after a successful call. You already have a function in your code so its a simple matter of updating that function. The second div that you will like to update can be loaded with AJAX too.

 $.ajax({
  //other options
  success:function(){
       commentContainer.slideUp('slow', function() {$(this).remove();});
       $('#otherdiv').load('urlofpagewith info.php');
  }

 });
Vincent Ramdhanie
Yes this is what I wanted! Actually just moments ago I found somewhere else .load thing and just not noticed where to put it.. :)Thank You!
Marko
+2  A: 

Simply expose the data parameter of the success callback and replace the contents of whichever element, in this example div id="someDiv":

$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(data){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    $('#someDiv').html(data);
  }
 });

See ajax options for more information.

Also, for the love of god don't use type names as variable names, it's really scary and terrible practice, even though string is not a reserved word in Javascript (use data: str or data: dataString instead).

karim79
A: 

almost all jquery functions have the ability to use callback functions. these are called whenever the original action is finished executing. so this can be used with any function, not just ajax.

contagious