0

I'm trying to create an Ajax like button for my Django project(Python's framework). Basically, what I'm doing is making a partial update on index.html when the Ajax call is a success. It works fine the first time, but when a button with the same id is clicked for the second time, it will reload the entire page, which is not what I expect. Could anyone teach me how to prevent this from happening?

I'm not sure if the Python side has anything to do with this, but I'm going to paste some of the codes anyway. Thank you.

main.js

  $('button').on('click', function(event){
      event.preventDefault();
      var element = $(this);
      $.ajax({
        url : element.attr("data-id") + '/like/',
        type : 'POST',
        data : { card_id : element.attr("data-id")},
        success : function(response){
          console.log(response);
          $('#like-area-' + element.attr("data-id")).load(document.URL +  ' #like-area-' + element.attr("data-id"));
        }
      })
    })


// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

templates/index.html

{% for card in cards %}

......


    <section id="like-area-{{ card.id }}">

        <!-- currently testing if ajax works properly with this button-->
        <form  method="post">
                {% csrf_token %}
                <button data-id="{{ card.id }}" class="btn btn-default">いいね</button>
        </form>

        <!-- ultimately I'd like to fire up ajax through this anchor tag -->
        <a id="like-button-{{ card.id }}" href="{% url 'like-post' card.id %}"><span class="glyphicon glyphicon-heart
        {% for your_like in your_likes %}
            {% if card  == your_like.liked_post %}
            red no-border
            {% endif %}
        {% endfor %}
        "></span></a> &nbsp;
    </section>

.....

{% endfor %}

views.py

def like_post(request, card_id):
    if Like.objects.filter(liker=request.user, liked_post = card_id).exists():
        existing_like = Like.objects.get(liker=request.user, liked_post = card_id)
        existing_like.delete()
        likes = Like.objects.all()
        is_liked = 0
        # return HttpResponse(likes)
        return HttpResponse(is_liked) #not really using this yet
    else:
        card = Card.objects.get(id=card_id)
        new_like = Like(liker=request.user, liked_post = card)
        new_like.save()
        # likes = Like.objects.all()
        likes = Like.objects.all()
        is_liked = 1
        return HttpResponse(is_liked) #not really using this yet

urls.py

url(r'^(?P<card_id>[0-9]+)/like/$', views.like_post, name='like-post'),
Yuta
  • 37
  • 8
  • 3
    `$(document).on( 'click' , 'button' , function(event){ // code here})` .. read [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Mohamed-Yousef Jun 09 '17 at 02:32
  • Thank you so much! Now it works like a charm! – Yuta Jun 09 '17 at 02:37

1 Answers1

0

I just read your request: ajax cần't click 2 time (need reload or it auto reload page)

~> Create a var for ajax and abort it.

var ajaxcall1
def ...
if (ajaxcall1)
        ajaxcall1.abort();
# some more code

You can try it, i just think you don't check the status. If not, i will check for more detail late

Nam Nguyễn
  • 552
  • 4
  • 20