Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax get API request append element to correct div

With Python I have created a feed from Facebook, which is loaded into this:

<div class="col-md-12"> 
<section id="cd-timeline" class="cd-container">
{% for item in merged  %} 
<div class="cd-timeline-block">
  <div class="cd-timeline-img cd-success">
            <i class="fa fa-tag"></i>
  </div> <!-- cd-timeline-img -->

  <div class="cd-timeline-content">
    <h2>{{item.1}}</h2>
    <p>{{item.5|safe}}</p>
    {% if  item.2 != '<p> </p>'%} 
    <p> <img src="{{item.2|safe}}"/> {% endif %} <p> {{item.3|safe}} {{item.4|safe}} </p> </p>
    <span class="cd-date">Jan 14</span>
        <div class="timeline-item-post">

   <div class="timeline-options">

    <a href="#"><i class="icon-like"></i> {{item.6}}</a>

    <button id="{{item.9}}"><i class="icon-bubble"></i> {{item.7}} </button>

    <a href="#"><i class="icon-share"></i>  {{item.8}}</a>

    </div>



    <textarea class="form-control" placeholder="Replay"></textarea>
       </div>  
  </div> <!-- cd-timeline-content -->
</div> <!-- cd-timeline-block -->
  {% endfor %}

Now if I click the button {{item.9}} I want a jQuery request, to load a JSON response for this element (item.9 which refers to the post id) without the page being loaded again and attach the div below to cd-timeline-content and display the JSON content in it.

<div class="timeline-comment">
<div class="timeline-comment-header">
 <img src="assets/images/avatar5.png" alt="">
  <p>Nick Doe <small>1 hour ago</small></p>
  </div>
  <p class="timeline-comment-text">Nullam quis risus eget urna mollis ornare vel eu leo.</p>
    </div>

This was the only idea I had but that looks stupid and it doesn't work. Copying javascript code for each post seems like a bad idea.

{% for item in merged  %} 
<script> 
$("#{{item.9}}").on('click', function() {
  alert('something');
    $.getJSON("data.json", function(data) {
        //Handle my response

    });
});
</script>
{% endfor %}

Appreciate the help.

like image 405
dk1990 Avatar asked Apr 14 '26 14:04

dk1990


1 Answers

Set a class thats the same for each button:

<button class="myEvent" id="{{item.9}}"><i class="icon-bubble"></i> {{item.7}} </button>

$('.myEvent').on("click",function(e){
    e.preventDefault();
    $.getJSON("data.json", function(data) {
    //Handle my response

    });

});

with this solution you get the entire json file not filtered by "item". the filter process ve to be done inside the function.

hope this help

like image 94
Vanojx1 Avatar answered Apr 16 '26 03:04

Vanojx1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!