简体   繁体   中英

Dynamic Content with Ajax and Laravel

I am new with laravel and i want to implement a dynamic ajax content for accordion. i have a list of contact groups and its members. Groups and members have a many to many relationship. The accordion should display all the groups and when clicked must display all members belonging to its group.

Now, i am able to display all my groups in the accordion in the for loop. When i click on the accordion, the id should be consoled. The issue is, just the first accordion's id is consoled when clicked. All other accordion are not having their id's consoled when clicked.

As concerned, only the first accordion has its related members being displayed in its panel, the rest is empty. How can i solve this issue?

HTML

 <legend>Display members from contact groups</legend> 
    @foreach($contactGroup as $contact)
    <button type ="button" value="{!! $contact->id !!}" class="accordion" id="contact"  name="contact">{!!$contact->first_name!!}</button>
    <div class="panel" id="labels">
    </label>
    </div>
    @endforeach

Ajax

<script type="text/javascript">
$("#contact").on("click", function(e) {
    e.preventDefault();

    console.log($(this).val)());
    $.ajax({type: "GET",
        url: "/ajax-request?contact_id=" +contact_id,
        data: 
        { contact_id: $(this).val(), 
          access_token: $("#access_token").val()   
         },
        success:function(result) {             
        $.each(result, function (i, myData) {    
        $("#labels").append('<label>'+myData.name+'</label>');                
    });

      },
            error:function(result) {
          alert('error');
        }   
    });   
});

</script>

Instead of referencing id=contact use class=accordion contact

and then in your ajax part

<script type="text/javascript">
$(".contact").on("click", function(e) {
    e.preventDefault();
    var $this = $(this);

    console.log($this.attr('value'));
    ....
    ..
    .
});

</script>

See this post to know the difference between Id and Class div class vs id

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