3

I am using django

In the body block

<div id="tag_like">
    {% if liked %}
      <img id="unlike" title="unlike" src="{{ STATIC_URL }}pic/bad.png" />
    {% else %}
      <img id="like" title="like" src="{{ STATIC_URL }}pic/good.png" />
    {% endif %}
</div>

In the on_ready script block:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
});
$('#like').click(function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});
$('#unlike').click(function() {
   $.post("{% url 'unlikevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});

It works fine at the 1st time you click the image.(turned to the other image) But when click it again, no ajax action happens. I read

Refresh a div in Django using JQuery and AJAX

jqgrid not reloading after making a ajax call using trigger('reload')

Adding jQueryui Buttons to dynamically added content

But no specific solution reached yet... Any solution with minimal changes?

Community
  • 1
  • 1
Leon
  • 75
  • 5

3 Answers3

1

Use .on() because you are loading DOM to div with ID of tag_like.

$(document).on('click','#like',function(){
    //code here.
});
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
1

try this for event binding:

$('#tag_like').on("click", "#like", function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});
$('#tag_like').on("click", "#unlike", function() {
   $.post("{% url 'unlikevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});
codefreak
  • 6,950
  • 3
  • 42
  • 51
0

Do it like:

$('#tag_like').on("click", "#like", function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});

This method is fast because it will prevent jQuery from parsing whole document each time you click on the button.

Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49