Martin Martin - 12 days ago 5
Ajax Question

Cannot update div without reloading page through jquery to display json data

I'm fetching the "like count" from django backend and I'm adding the right value in the respective field. However I need to reload the page in order for the value to be updated.
The problem is that the html code includes classes, not ids since the idea is to have a lot of "similar" posts (like a feed of posts).

I've tried different ways of reloading just the div that includes the like button but have failed so far. any ideas would be appreciated!

I want to handle the reloading in the frontend

$(document).on('click', ".like_post", function(e){
var self = $(this);
$.ajax({
type: 'GET',
url: self.data("url"),
dataType: 'json',
success: function(data) {
self.children("p").text(data["count"]);
},
});
});


I'm attaching the html code, imagine each "card" as each of the post generated on the site:

<div class="card>
<div class="card-heading"></div>
<div class="card-body"></div>
<div class="card-actions">
<a class="btn .like_post" data-url"">
<ul>
<li><p>like count</p></li>
<li>like image</li>
</ul>
</a>
<a class="btn .share_post" data-url"">
<ul>
<li>share count</li>
<li>share image</li>
</ul>
</a>
</div>
</div>

Answer

I found two issues in your code and it worked after correcting them.

  1. anchor tag has the class as .like_post instead of like_post in <a class="btn .like_post" data-url""> which didn't trigger the click event
  2. self.children("p") is not returning the element since the self.children() is returning the immediate child <ul>. Hence, it has been changed to self.find("p").

Also add event.stopPropagation() if your anchor tag has any href element and make sure your ajax request returns data.

Note: To check this, I have commented $.ajax code and used setTimeout to simultate the ajax response waiting.

$(document).on('click', ".like_post", function(e){
  e.stopPropagation();
    var self = $(this);
    /*$.ajax({
        type: 'GET',
        url: self.data("url"),
        dataType: 'json',
        success: function(data) {
            self.find("p").text(data["count"]);
    },
    });*/
  
  setTimeout(function(){
    var data = {count: 10};
    //console.log(self.children());
    self.find("p").text(data["count"]);
  }, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
 <div class="card-heading"></div>
 <div class="card-body"></div>
 <div class="card-actions">
  <a class="btn like_post" data-url"">
   <ul>
    <li><p>like count</p></li>
    <li>like image</li>
   </ul>
  </a>
  <a class="btn .share_post" data-url"">
    <ul>
      <li>share count</li>
      <li>share image</li>
    </ul>
  </a>
 </div>
</div>