Mohit Harshan
Mohit Harshan

Reputation: 1986

ajax like button django

my ajax jquery :

 $(".likebutton").on('click', function () {
  post_id=$(this).attr('name');
  console.log('CLICKED IN LIKE');
    $.ajax({

    dataType: 'json',

    url: post_id +'/like/',
    data: {


  },
  success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
   m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
  'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
 </i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
    </i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
 }
});
 });

my like template like_comment2.html:

<p class="pull-left m-r-15"> {{ obj.like.count }} Likes </p>

<form action="{% url 'student:like' pk=obj.id %}" method="POST">
{% csrf_token %}
 <input type="submit" value="Like" name="{{ obj.id }}" 
class="likebuttons m- 
r-15 text-inverse-lighter" {% if request.user in obj.like.all %} 
style="color: blue" {% endif %}"></input><i class="fa fa-thumbs-up fa- 
fw 
fa-lg m-r-3"></i>


</form>

My view:

def LikeToggleView(request,pk=None):
print("NOT AJAX")
if request.is_ajax():
    post_id = request.POST.get('post_id')
    response_data = {}
    obj = get_object_or_404(Task, pk=post_id)

    user = request.user

    print("AJAX LIKE")

    if user in obj.like.all():
             obj.like.remove(user)
             note = Notification.objects.create(sender=user, task=obj, 
 notification = user.username + ' Disliked Your Post ' + obj.title)
             note.receiver.add(obj.student)
    else:
             obj.like.add(user)
             note = Notification.objects.create(sender=user, task=obj, 
  notification = user.username + '  Liked Your Post ' + obj.title)
             note.receiver.add(obj.student)



    response_data['likecount'] = obj.like.count

    return JsonResponse(response_data)

I want to update the number of likes in the template using ajax.Seems like its not getting into the ajax call :It printing "Not AJax" in the terminal

my urls.py

url(r'^dashboard/tasks/(?P<pk>\d+)/like/$', views.LikeToggleView, 
name='like'),

The console is showing errors: GET http://localhost:8000/student/dashboard/tasks/154/like/ 404 (Not Found) http://localhost:8000/student/dashboard/tasks/154/like/ 404 (Not Found)

14:21:37.896 :8000/student/dashboard/tasks/154/like/:1 POST http://localhost:8000/student/dashboard/tasks/154/like/ 500 (Internal Server Error) Also its firing the jquery onclick two times when i click on like button

urls.py:

from django.conf.urls import url
from . import views

app_name = 'student'

urlpatterns=[
url(r'^dashboard/tasks/$',views.StudentDashView,name='dashboard'),
url(r'^dashboard/tasks/ajax/reload/$', views.ajax_change_status, 
name='ajax_change_status'),

url(r'^dashboard/tasks/(?P<pk>\d+)/$', views.TaskDetailView, 
name='task-detail'),
url(r'^dashboard/tasks/(?P<pk>\d+)/like/$', views.LikeToggleView, 
name='like'),
url(r'^add-mentor/$',views.AddMentor,name='add_mentor'),
url(r'^trainer-profile/(?P<trainer_id>\d+)/$', 
views.TrainerPublicProfile, name='trainer_public_profile'),
url(r'^add-as-mentor/(?P<pk>\d+)/$', views.AddAsMentor, 
name='add_as_mentor'),
url(r'change-as-mentor/(?P<pk>\d+)/$', views.ChangeAsMentor, 
name='change_as_mentor'),
url(r'^accept-to-hub/(?P<pk>\d+)/(?P<notify>\d+)/$', views.AcceptHub, 
name='accept_hub'),
url(r'^reject-to-hub/(?P<pk>\d+)/(?P<notify>\d+)/$', views.RejectHub, 
name='reject_hub'),
url(r'^accept-mentor/(?P<pk>\d+)/$', views.AcceptMentor, 
name='accept_as_mentor'),
url(r'^reject-mentor/(?P<pk>\d+)/$', views.RejectMentor, 
name='reject_as_mentor'),
url(r'^promote-to-excom/(?P<user>\d+)/$', views.PromoteExcom, 
name='promote'),
url(r'^depromote-to-excom/(?P<user>\d+)/$', views.DePromoteExcom, 
name='depromote'),
url(r'^remove-from-hub/(?P<user>\d+)/$', views.RemoveFromHub, 
name='remove_from_hub'),

url(r'^view-hubs/$', views.HubListView, name='view_all_hubs'),
url(r'^join-hub/(?P<pk>\d+)/$', views.JoinHub, name='join_hub'),

# url(r'^dashboard/tasks/(?P<task_id>\d+)/like/$', views.Tasklike, 
name='task-like'),
url(r'^level/$', views.StudentLevelListView, name='level'),
url(r'^level/(?P<pk>\d+)/$', views.StudentLevelDetailView, 
name='level-detail'),
url(r'^level/(?P<pk>\d+)/(?P<todo_id>\d+)/$', views.TaskCreateView, 
name='task-form'),
url(r'^hub/$', views.StudentHubListView, name='hub'),
url(r'^subscribe/member/$',views.MemberPay,name='member'),
url(r'^subscribe/fellow/$', views.FellowPay, name='fellow'),
url(r'^payment-member/success$', views.payment_success_member,  
name="payment_success_member"),
url(r'^payment-member/failure$', views.payment_failure_member, 
name="payment_failure_member"),
url(r'^payment-fellow/success$', views.payment_success_fellow, 
name="payment_success_fellow"),
url(r'^payment-fellow/failure$', views.payment_failure_fellow, 
name="payment_failure_fellow"),

]

js:

 $(".likebutton").on('click', function (event) {
 event.preventDefault();
 post_id=$(this).attr('value');
  console.log('CLICKED IN LIKE');
    $.ajax({
type:'post',
    url: post_id+'/like/',
    data: {
  csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

    },

 success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
  m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
 'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
 </i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
</i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
},
     crossDomain: false


});
 });



 $(".likebuttons").on('click', function (event) {
  event.preventDefault();
 post_id=$(this).attr('value');
 console.log('CLICKED IN LIKE');
    $.ajax({
     headers: {'X-Requested-With': 'XMLHttpRequest'},
 type:'post',
    url: 'like/',
    data: {
  csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

    },

 success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
 m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
 'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
</i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
</i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
},

    crossDomain: false


 });
});

I have included like section from here:

 <div class="timeline-footer">

   {% include 'like_comment2.html' %}
    <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i 
 class="fa fa-comments fa-fw fa-lg m-r-3"></i>
        Comment</a>
  </div>

Upvotes: 0

Views: 813

Answers (2)

Mohit Harshan
Mohit Harshan

Reputation: 1986

This is the final working code:

Javascript:

$(document).on('click','.likebutton',function(event)  {
event.preventDefault();
post_id=$(this).attr('value');
console.log('CLICKED IN LIKE');
    $.ajax({
    url: post_id+'/like/',
 type:'post',

    data: {
  csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

 },

  success: function (data) {

       console.log("SUCCESS")
       console.log(data);
        console.log($(this).closest("div").prop("class"));
        $(this).closest('div').html(data)

        // here you update the HTML to change the active to innactive

  }.bind(this),
 error: function(xhr, status, error) {
 var err = JSON.parse(xhr.responseText);
 alert(err.Message);
}

 });
 });

My function:

 def LikeToggleView(request,pk=None):


    obj = get_object_or_404(Task, pk=pk)

    user = request.user


    if user in obj.like.all():
             obj.like.remove(user)
             note = Notification.objects.create(sender=user, task=obj, 
  notification = user.username + ' Disliked Your Post ' + obj.title)
             note.receiver.add(obj.student)
    else:
             obj.like.add(user)
             note = Notification.objects.create(sender=user, task=obj, 
  notification = user.username + '  Liked Your Post ' + obj.title)
             note.receiver.add(obj.student)


    if request.is_ajax():
     print("AJAX LIKE")
     context={
        'obj':obj,

     }
     html = render_to_string('like_comment.html', context, request=request)
     return HttpResponse(html)

like_comment.html:

 {% load static %}

 <p class="pull-left m-r-15"> {{ obj.like.count }} Likes </p>

 <form action="{% url 'student:like' pk=obj.id %}" method="POST">
 {% csrf_token %}
 <a href="" type="submit" value="{{ obj.id }}" name="post_id"   
 class="likebutton m-r-15 text-inverse-lighter" {% if request.user in o 
Obj.like.all %} style="background: blue" {% endif %}">Like</a><i class="fa fa- 
thumbs-up fa-fw fa-lg m-r-3"></i>


</form>
 <a href="{% url 'student:task-detail' obj.id %}" class="m-r-15 text-inverse- 
 lighter"><i
                        class="fa fa-comments fa-fw fa-lg m-r-3"></i>
                    Comment</a>

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599630

It's not actually firing twice, it's firing the Ajax post but then immediately the browser submits the page to the same URL.

You need to prevent the default submit action in your JS:

$(".likebutton").on('click', function(event) {
    event.preventDefault();
   ...
});

Upvotes: 1

Related Questions