bootstrap load collapse panel with ajax

15,319

Solution 1

I kind of solved it by adding a "open" class when loaded with data, and removing that same class if clicked when opened:

$('#accordion a').click(function () {
      if($(this).hasClass("panelisopen")){
          $(this).removeClass("panelisopen");
      } else {
          var href = this.hash;
          var depId = href.replace("#collapse",""); 

          $(this).addClass("panelisopen");

          var dataString = 'depId='+ depId + '&dep=1&do=getDepUsers';
          $.getJSON(dir_pre + 'ajax/users.php?' + dataString, function(data) {
              $('#depUsers'+depId).html(data);
          });
      }
  });

Not the best solution I guess, but it works.

Solution 2

You can try this:

$('#accordion').on('show.bs.collapse', function(e){
   var depId  = $(e.target).attr('id').replace('collapse','');
   ...
});
Share:
15,319
netcult
Author by

netcult

Updated on June 13, 2022

Comments

  • netcult
    netcult about 2 years

    I'm trying to load collapsable panels with ajax. I got it working, but my trigger fires on the a tag, so the ajax script is called when you open AND close the panel. It should not load it when you close the panel, this is overload..

    My code:

    <div class="panel-group" id="accordion">    
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href="#collapse1">First panel</a></h4>
        </div>
        <div id="collapse1" class="panel-collapse collapse">
            <div class="panel-body">
                  <div id="depUsers511"><!-- here users will be loaded through ajax --></div>
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Second panel</a></h4>
        </div>
        <div id="collapse2" class="panel-collapse collapse">
            <div class="panel-body">
                  <div id="depUsers511"><!-- here users will be loaded through ajax --></div>
            </div>
        </div>
    </div>
    

    The javascript:

    $('#accordion a').click(function () {
    
        var collapse_element = event.target;
        alert(collapse_element);
    
        var href = this.hash;
        var depId = href.replace("#collapse",""); 
    
        var dataString = 'depId='+ depId + '&do=getDepUsers';
        $.getJSON(dir_pre + 'ajax/users.php?' + dataString, function(data) {
            $('#depUsers'+depId).html(data);
        });
     })
    

    The ajax script returns the content of the div. So, it works, but I'm looking for the correct way to fire the ajax load trigger... i think I need to use the "show.bs.collapse" event, but can't find out how to use this on a panel which contains more than one dynamic panel (with its own ID).

    Thanks for your help!

    M.