user8733268
user8733268

Reputation:

Updating Like Button Without Page Refresh

I'm working on a Like button. It's working fine. After Like button completes it's functionality I'm trying to update the button text (Like to Liked) without refreshing the page, but problem is that It's updating the every single Like button on the webpage (until I refresh the page) not just the one I clicked on . . .

Here's that success function in AJAX call,

$('.like-click').click(function(e){
e.preventDefault();

var this_ = $(this);
var quesURL = this_.attr('like-href');
$.ajax({
    url: quesURL,
    method: 'GET',
    data: {},
    success: function (data) {
        var like_text = $(data).find('.like-click').html();
        $('.like-click').html(like_text);
    }
})
});

Here's the HTML code,

{% for data in datas %}
     ...
     <a class="like-click" like-href="...">{% if user in Likes %}Liked{% else %}Like{% endif %}</a>
     ...
{% endfor %}

How can I update the button I clicked, not all of them ?

Upvotes: 0

Views: 1864

Answers (3)

user9009639
user9009639

Reputation:

Why you use AJAX for this? You are not pulling "Like" or "Liked" from database. Do it with simple handler:

$(function(){
    $('button').click(
       function(){
         $(".button div").toggle();
       }
    )
});


<button type="button" class="button like-click">
  <div>Like</div>
  <div style="display: none">Liked</div>
</button>

And note, that selecting button / a element by class="like-click" is probably not what you need (it would affect all elements by that class), so better asing them ids that are unique and comes from your {% for data in datas %} loop

UPDATE:

Because you dont have a dislike, it could be done in same manner as in my above example:

<button type="button" class="button" id="btn">
  <div class="like">Like</div>
  <div style="display: none" class="like">Liked</div>
  <div class="count" id="current"> 1 </div>  
  <div style="display: none" class="count" id="clicked">  </div> 
</button>

$('#btn').click(function() {
    $('#btn #clicked').html(parseInt($('#current').text()) + 1);
    $('#btn .like').toggle();
    $('#btn .count').toggle();  
})

Upvotes: 0

wahmal
wahmal

Reputation: 947

that's happened because you firing all button with having 'like-click' class

$('.like-click').click(function(e){
e.preventDefault();
var this_ = $(this);
var quesURL = this_.attr('like-href');
$.ajax({
   url: quesURL,
   method: 'GET',
   data: {},
   success: function (data) {
    if(this_.html()=='like'){
      this_.html('liked');
    }else{
      this_.html('like'); 
    }
   }
})
});

Upvotes: 0

Kishan
Kishan

Reputation: 793

You have saved your clicked element in var this_, so you have to just update that element text only via replacing $('.like-click').html(like_text); to $(this_).html(like_text);

So it will not update each button text.

Upvotes: 1

Related Questions