Search code examples
jqueryajaxdjangoreload

jquery ajax item can not be clicked after reload


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?


Solution

  • 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')
       });
    });