简体   繁体   中英

Send AJAX request by clicking a link inside a dynamically created bootstrap accordion

I have a dynamically created accordion like this:

<div class="panel-body">
<div class="panel-group" id="accordion">

   <div class="panel panel-default" >
      <div class="panel-heading">
         <h5 class="panel-title small">
            <a data-toggle="collapse" data-parent="#accordion" href="#1" class="tasktitle" data-id="1" id="opentask">$name</a>
         </h5>
      </div>
      <div id="1" class="panel-collapse collapse">
         <div class="panel-body">body text</div>
      </div>

   <div class="panel panel-default" >
      <div class="panel-heading">
         <h5 class="panel-title small">
            <a data-toggle="collapse" data-parent="#accordion" href="#2" class="tasktitle" data-id="2" id="opentask">$name</a>
         </h5>
      </div>
      <div id="2" class="panel-collapse collapse">
         <div class="panel-body">body text</div>
      </div>

   </div>
</div>

Then I have a static value like $loggeduser which is always the same for the logged user.

As this is a dynamically created accordion though, the id of each accordion section is different

What I am trying to achieve is when the user click to open the accordion, in the same time to execute an AJAX request which will send the value of the $loggeduser together with the id of the accordion in which the clicked link is placed in.

This is the ajax I am using to send the info to the file

$(function(){    
   $("#opentask").click(function(){
      $.get("markread-task.php?id=ID&user=LOGGEDUSERCOMMENT",function(data){
     });
   });
  return false;    
});

but I cant figure out how to to have a different ID in this link

markread-task.php?id=ID&user=LOGGEDUSERCOMMENT

for example if the user click on the link that opend accordion 2, the ajax sends link like

markread-task.php?id=2&user=LOGGEDUSERCOMMENT

Thanks for your help

First of all, Id must be unique to each element. Use class or name instead. So you cannot have two elements with id="opentask".

To get data-id value in your click method:

$(function(){    
   $(".opentask").click(function(){
      var id = $(this).data('id');
      $.get("markread-task.php?id="+id+"&user=LOGGEDUSERCOMMENT",function(data){
     });
   });
  return false;    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM