DrXCheng
DrXCheng

Reputation: 4132

How to avoid duplicate AJAX when doing toggle?

I have the following jQuery code:

$('.button').click(function(e) {
  e.preventDefault();

  var id = $(this).attr('id');
  var panel = $('#picpanel' + id);
  var panelhtml = '<ol id="piclist' + id + '" class="piclist"></ol>';
  panel.html(panelhtml);
  panel.slideToggle(200);
  $(this).toggleClass('active');

  $.ajax({
    type: 'GET',
    url: 'index.php',
    data: 'id=' + id + '&submit=getpicture',
    cache: false,
    success: function(html) {
      $('#piclist' + id).append(html);
    }
  });
});

Basically, the pictures are read from database upon clicking a button. A panel showing all the pictures is also hidden before clicking the button. When I click the button, the panel is shown, and pictures are read and shown; there is no problem.

The problem is, when I click the button again, I want to hide the panel. It can be hidden, but it seems the AJAX runs again, which is of course unwanted. How to avoid that?

Upvotes: 0

Views: 325

Answers (1)

Kai Qing
Kai Qing

Reputation: 18843

Check to see if the element has an active class and only run if it does not.

if(!$(this).hasClass("active"))
{
  $.ajax({
    type: 'GET',
    url: 'index.php',
    data: 'id=' + id + '&submit=getpicture',
    cache: false,
    success: function(html) {
      $('#piclist' + id).append(html);
    }
  });
}

Additionally, if you want the element to only run ajax once and not just if it has an active class you can add a class on the first ajax and then check the has class on the new class instead...

if(!$(this).hasClass("fetched"))
{
  $.ajax({
    type: 'GET',
    url: 'index.php',
    data: 'id=' + id + '&submit=getpicture',
    cache: false,
    success: function(html) {
      $('#piclist' + id).append(html);
    }
  });
  $(this).addClass("fetched");
}

btw I add the class in the if and not in the success because the ajax will call success even if it failed. You can choose to do it however you want of course.

Upvotes: 1

Related Questions