Bolaji Bolaji - 5 months ago 9
Ajax Question

How to make Ajax change a variable on success

I want to implement a like button for a feed using Jquery Ajax.On a feed-page.html.The code works by making a user like or unlike a feed but how can I make

<p id='count'>
reload ajaxly on hitting
Like
button?
Thanks for your help in advance

<p>{{feed_detail.text|linebreaks}} </p>
<p id='count'> {{feed_detail.total_likes}} concern{{feed_detail.total_likes|pluralize:'s'}}</p>
<p> {{feed_detail.pub_date|naturaltime|capfirst}} </p>
<input type="button" id="like" name="{{feed_detail.slug}}" value="Like" />
<script>
$('#like').click(function(){

$.ajax({

type: "POST",
url: "{% url 'like' %}",
data: {'slug': '{{feed_detail.slug}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
});
})
</script>

Answer

Try something like this,change the input to type checkbox

<p id='count'><span>{{feed_detail.total_likes}}</span> concern{{feed_detail.total_likes|pluralize:'s'}}</p>
<input type="checkbox" id="like" name="{{feed_detail.slug}}" value="Like" />
    $('#like').click(function(){
      var el = $(this);
          $.ajax({

                   type: "POST",
                   url: "{% url 'like' %}",
                   data: {'slug': '{{feed_detail.slug}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                   dataType: "json", 
                   success: function(data){
                      if (el.is(':checked')) {
                       $('#count span').text(parseInt($('#count span').text())+1);
                      } else {
                      $('#count span').text(parseInt($('#count span').text())-1);
                      }
                   }
              }); 
        });

demo: https://jsfiddle.net/gxup1wpo/