How to iterate django template variable in the jQuery selected element? - javascript

I am working on a chat system in which I can open multiple chat of users (just like facebook).
When the user clicks on the username that is in the contact list, a chat popup gets open.
models.py:
class ThreadManager(models.Manager):
def by_user(self, **kwargs):
user = kwargs.get('user')
lookup = Q(first_person=user) | Q(second_person=user)
qs = self.get_queryset().filter(lookup).distinct()
return qs
class Thread(models.Model):
first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person')
second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
related_name='thread_second_person')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ThreadManager()
class Meta:
unique_together = ['first_person', 'second_person']
class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread')
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
Following is a query that I pass from views.py to my html template:
threads = Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread')
Following is the html code:
<div class="chat_box">
<div class="chat_header" >
<h1 class="chat_heading">(6) Contacts</h1>
</div>
<hr>
<div class="chat_content" style="display: none;">
{% for thread in Threads %}
<div class="user" id="{{ thread.second_person.id }}" thread-id = "{{thread.id}}" chat-id="chat_{{ thread.id }}">
<img id="my_img" src="{{user_personal.picture.url}}" class="user_icon">
{% if thread.first_person == user %}
<h3 class="username">{{ thread.second_person.first_name }} {{ thread.second_person.last_name }}</h3>
{% else %}
<h3 class="username">{{ thread.first_person.first_name }} {{ thread.first_person.last_name }}</h3>
{% endif %}
<i class="fa fa-circle"></i>
</div>
{% endfor %}
</div>
</div>
Following is the jquery code:
$(".user").click(function(){
var userID = $(this).attr("id");
var threadid = $(this).attr("thread-id");
var username = $(this).children().text();
profile_pic = $('#my_img').attr('src');
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="message_box" style="right:290px" rel="'+ userID+'" thread-id="'+threadid+'"><div class="message_header" rel="'+ userID+'">'+
'<img src="http://127.0.0.1:8000'+profile_p+'" class="user_icon"><h3 class="username">'+username+'</h3>'+
'<i class="fa fa-times close" rel="'+ userID+'"></i></div><hr><div class="message_content"><div class="messages" rel="'+ userID+'">'+
'<div class="chat">'+
'{% for thread in Threads %}{% for chat_i in thread.chatmessage_thread.all %}'+
'{% if thread.first_person.id == user.id and thread.second_person.id == 3 %}'+
'{% if thread.id == chat_i.thread_id %}'+
'{% if chat_i.user == user %}'+
'<div class="new_messages p2"><p>{{ chat_i.message }}</p></div>'+
'{% else %}'+
'<div class="new_messages p1"><p>{{ chat_i.message }}</p></div>'+
'{% endif %}{% endif %}{% endif %}{% endfor %}{% endfor %}</div></div><div class="input_box">'+
'<textarea type="text" class="message_input" rel="'+ userID+'" placeholder="Type Message..."></textarea>'+
'<i class="fa fa-arrow-circle-right enter" rel="'+ userID+'"></i></div></div></div>';
if ( $('[rel="'+userID+'"]').length == 0) {
$("body").append( chatPopup );
console.log(chatPopup);
displayChatBox();
}
});
Client side functionalities are working totally fine but I am not able to iterate chat messages based on a specific thread id.
The messages are displaying on all the chat popups.

Try inserting loop over chatmessage_thread after the if statements.
The second if statement if thread.id == chat_i.thread_id is always correct and is useless, as you are fetching chat_messages of that thread. omit it and insert the loop after first if (if thread.first_person.id == user.id and thread.second_person.id == 3)

Related

Need to save all answers from a user on every questions related on a specific Quiz

I want to save after submitting all answers from a user of all questions related on a specific Quiz.
The logical is :
I've got Quiz, Questions. Question car link to Quiz and when I choose a quiz all questions link to are shown on webpage with javascript (design).
After submiting I need to get all checkbox checked and save into UserResponse.
Models
class Question(models.Model):
objects = None
question = models.CharField(max_length=200, null=True)
description = models.CharField(max_length=255, null=True)
question_pic = models.ImageField(upload_to='poll/', storage=fs, null=True)
choices = models.ManyToManyField(Answer, related_name='QuestionsChoices')
mandatory = models.BooleanField(default=True)
multiple = models.BooleanField(default=False)
randomize = models.BooleanField(default=False)
class Quiz(models.Model):
STATUS_CHOICES = (
(1, 'Draft'),
(2, 'Public'),
(3, 'Close'),
)
nom = models.CharField(max_length=200, null=False)
theme = models.ForeignKey(Theme, null=False, on_delete=models.CASCADE)
questions = models.ManyToManyField(Question, related_name='Quizs')
status = models.IntegerField(choices=STATUS_CHOICES, default=1)
published = models.DateTimeField(null=True)
date_added = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now_add=True)
class QuizInstance(models.Model):
objects = None
"""
A combination of user response and a quiz template.
"""
player = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
start_quiz = models.DateTimeField(auto_now_add=True)
score = models.IntegerField(default=0)
complete = models.BooleanField(default=False)
class UserResponse(models.Model):
objects = None
"""
User response to a single question.
"""
quiz_instance = models.ForeignKey(QuizInstance, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
response = models.ManyToManyField(Answer, related_name="UserResponses")
time_taken = models.DateTimeField(auto_now_add=True)
time_taken_delta = models.DateTimeField(blank=True)
VIEWS (to show all questions from selected quiz)
def show_quiz(request, quiz_id):
try:
quiz = Quiz.objects.get(pk=quiz_id)
except:
messages.error(request, "Ce quiz n'existe pas ;)")
return redirect('poll:show-list')
context = {
'quiz': quiz,
}
return render(request, "poll/show_quiz.html", context)
# IF QUIZ SUBMITED, HERE I NEED TO SAVE ALL ANSWER GAVE BY USER INTO UserResponse
def answer_quiz(request):
context = {}
if request.method == 'POST':
quiz = Quiz.objects.get(pk=request.POST.get('id_quiz'))
player = request.user
quiz_player = QuizInstance.objects.filter(player=player, quiz=quiz)
if len(quiz_player) == 0:
quiz_instance = QuizInstance.objects.create(player=player, quiz=quiz)
else:
context = {
'error': True,
}
return render(request, "poll/answer_quiz.html", context)
TEMPLATES (HTML)
[...]
{% for question in quiz.questions.all %}
<fieldset class="p-4" style="max-width:720px; margin:0 auto;">
<question>
{{ forloop.counter }} - {{ question.question }}
{% if question.question_pic != "" and question %}
<div class="col-12 my-3 rounded-3" id="picQuestionDiv">
<img class="img-thumbnail rounded-3 p-2" src="/media/{{ question.question_pic }}" width="200" />
</div>
{% endif %}
</question>
<reponses class="d-grid gap-4" style="display:block !important; ">
{% if question|is_answer_pic %}
{% for reponse in question.choices.all %}
<input type="checkbox" hidden value="{{ reponse.id }}" name="reponse" id="reponse_{{ reponse.id }}" />
<reponse style="width:calc(50% - 8px + 4px); text-align:left !important;" class="col-6 mb-2 btn btn-reponse reponse" data-id="reponse_{{ reponse.id }}">
<div class="d-flex align-items-center rounded-3">
{% if reponse.answer_pic %}
<img class="card-img-top rounded-3 img-fluid mh-100 cover text-center" style="" src="/media/{{ reponse.answer_pic }}">
{% else %}
<i class="card-img-top rounded-3 mt-2 img-fluid mh-100 cover bi bi-eye-slash fs-1 text-center"></i>
{% endif %}
</div>
<div style="display:inline-block">
<span class="border border-secondary p-0 px-2 rounded-3 letter-reponse-pic bg-light text-secondary" style="">{{ forloop.counter0|show_letter }}</span>
<span class="">{{ reponse.answer }}</span>
</div>
</reponse>
{% endfor %}
{% else %}
{% for reponse in question.choices.all %}
<reponse style="width:calc(50% - 8px + 4px);" class="col-6 mb-2">
<div class="d-flex align-items-center rounded-3 border btn btn-outline-reponse p-2 reponse mb-2">
<span class="border border-secondary p-0 px-2 rounded-3 letter-reponse bg-light text-secondary">{{ forloop.counter0|show_letter }}</span>{{ reponse.answer }}
</div>
</reponse>
{% endfor %}
{% endif %}
</reponses>
<link class="" style="display: block;">
{% if not forloop.first %}
<a class="btn btn-secondary prev">Précédente</a>
{% endif %}
{% if not forloop.last %}
<a class="btn btn-secondary next">Suivante</a>
{% endif %}
{% if forloop.last %}
<button type="submit" class="btn btn-success next">Terminé !</button>
{% endif %}
</link>
</fieldset>
{% endfor %}
I know my method is not very clean ... I use form for Create Question, Quiz, etc ... but for showing Question I can't because need to show specific kind of checkbox if image, and other if not ... Anyway, here my need it just to retrive from POST submitting all data from quiz send by user And save it :)
Thanks for your help

What do I need to do if I want to use database data conditionally in Django templates?

I am working on an ecommerce store in Django. I want to know that how do I use the database data passed to templates using render() method, conditionally through JavaScript or AJAX or JSON?
For example, let's say I have a following models.py:
from django.db import models
class Suit(models.Model):
title = models.CharField(max_length = 100, verbose_name = "Title")
img = models.FileField(upload_to = 'suit-products/', null = True, verbose_name = "Picture")
def __str__(self):
return f"{self.title}"
class Buttoning(models.Model):
title = models.CharField(max_length = 100, verbose_name = "Title")
img = models.FileField(upload_to = 'buttonings/', null = True, verbose_name = "Picture")
def __str__(self):
return f"{self.title}"
and following views.py
from django.shortcuts import render
def index(request):
suit_prods = Suit.objects.all()
buttoning = Buttoning.objects.all()
context {
"suit_prods": suit_prods,
"buttoning": buttoning
}
return render(request, "index/index.html", context)
and following index.html (template):
{% for element in suit_prods %}
<li>
<a href="#">
<div id="menu">
<img src="{{ element.img.url }}" />
<span>{{ element.title }}</span>
<span></span>
</div>
</a>
</li>
{% endfor %}
Now what I want is, if the clicked element in the list items in index.html has the title as "two_piece_suit" then show items of {{ buttoning }} as a list, otherwise pass.
If I explain it more using some JS syntax, then I want following kind of behaviour:
<scrip>
var suit_menu = document.getElementsByClassName("menu");
for(var i = 0; i < suit_menu.length; i++) {
if(suit_menu.text == "two_piece_suit") {
{% for element in buttoning %}
<li>
<a href="#">
<div id="buttoning">
<img src="{{ element.img.url }}" />
<span>{{ element.title }}</span>
<span></span>
</div>
</a>
</li>
{% endfor %}
}
}
</script>
If I understand correctly, you don't necessarily need JavaScript to achieve this. Also, <script> is missing a t, and your for loop doesn't seem to add the HTML to the document at all.
You can achieve that purely with the Django Template Language by integrating the buttons for loop with an if condition like this:
{% if element.title == 'two_piece_suit' %}
{% for button in buttoning %}
<Some HTML>{{ button.title }}</Some HTML>
{% endfor %}
{% endif %}
That way, the list of buttons is only displayed if the title is two_piece_suit.

How to update a single field from modal form in Django?

I have a form that keeps track of when people enter/leave different areas. Whenever there is a discrepancy, for example, someone forgets to "leave" an area before entering a new one, the user is prompted an "estimate" of the time they believe they left the previous area at(edited_timestamp). The only two required fields on the main form are the employee number and the work area, as these are used to verify/keep track of data.
When I try to reproduce the situation that would make the modal show up, it works, but when I attempt to submit it, I get these messages:
and these are the errors that are being returned.
Now, while I don't understand why the "Enter valid date/time" error is showing, I'm guessing the other two errors are due to the main form requiring the employee_number and the work_area and probably for this request, even though it is updating by the ID, it still wants the other two fields.
I guess my question is, how could I modify this so that these two fields are not required for the modal?
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area")
station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True)
edited_timestamp = models.DateTimeField(null=True, blank=True)
time_exceptions = models.CharField(max_length=2, blank=True, default='', choices=EXCEPTION_STATUS)
time_in = models.DateTimeField(help_text="Time in", null=True, blank=True)
time_out = models.DateTimeField(blank=True, help_text="Time out", null=True)
forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number', 'edited_timestamp')
urls.py
urlpatterns = [
url(r'enter-exit-area/$', views.enter_exit_area, name='enter_exit_area'),
url(r'update-timestamp-modal/(?P<main_pk>\d+)/$', UpdateTimestampModal.as_view(), name='update_timestamp_modal'),
]
(Took out leave_area code for redundancy)
views.py
def enter_exit_area(request):
form = WarehouseForm()
enter_without_exit = None
exit_without_enter = None
if request.method == 'POST':
temp = request.POST.copy()
form = WarehouseForm(temp)
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in request.POST:
new_entry = form.save()
EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())
# If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N', meaning they're getting the modal
enters_without_exits = EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).exclude(pk=new_entry.pk).order_by("-time_in")
if len(enters_without_exits) > 0:
enter_without_exit = enters_without_exits[0]
enters_without_exits.update(time_exceptions='N')
message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
form = WarehouseForm()
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
})
class UpdateTimestampModal(CreateUpdateModalView):
main_model = EmployeeWorkAreaLog
model_name = "EmployeeWorkAreaLog"
form_class = WarehouseForm
template = 'operations/modals/update_timestamp_modal.html'
modal_title = 'Update Missing Time'
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
<script src="{% static "js/operations/warehouse_enter_exit.js" %}"></script>
{% endblock head %}
{% block main %}
{% if enter_without_exit %}
<div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" enter_without_exit.id %}" class="hidden"></div>
{% endif %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div>
<div style="color: red">{{ form.employee_number.errors.as_text }}</div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<div style="color: red">{{ form.work_area.errors.as_text }}</div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div style="color: red">{{ form.station_number.errors.as_text }}</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% modal id="create-update-modal" title="Update Timestamp" primary_btn="Submit" default_submit=True %}
update_timestamp_modal.html
{% load core_tags %}
<form id="create-update-form" method="post" action="{% url "operations:update_timestamp_modal" main_object.id %}">
{% csrf_token %}
<label>Update</label>
<div class="row">
<div class="form-group col-xs-6">
{% standard_input form.edited_timestamp datetimepicker=True hide_label=True %}
</div>
</div>
</form>
warehouse_enter_exit.js
$(function () {
// Submit the edited timestamp form when they click the "Submit" button in the modal
$(document).on('click', '#update-timestamp-modal-btn-primary', function (e) {
e.preventDefault();
forms.ajaxSubmit($('#create-update-form'), function (data) {
if (data.success && data.redirect) {
window.location.href = data.redirect;
} else {
if (data.warning) {
messages.warning(data.warning);
} else {
messages.error("An error occurred when saving this timestamp, please try again.");
}
}
});
});
});
Could I maybe edit the JS to only update the edited_timestamp field? Or maybe a way I can edit the views so that only that ID is accessed to update that field? The URL to the modal access it based on ID so I thought there could be a way to edit only based on this field.
You'll need to override those fields in your form code.
Like this:
class WarehouseForm(AppsModelForm):
employee_number = forms.ModelChoiceField(queryset=EmployeeWorkAreaLog.objects.all(), required=False)
work_area = forms.CharField(required=False)
class Meta...

Django 1.10 - Ajax - order of operations?

I am using Ajax with Django 1.10 to implement a like functionality ( a user likes an image posted by another user) on my website. I have the following code :
The views file :
#ajax_required
#login_required
#require_POST
def image_like(request):
image_id = request.POST.get('id')
action = request.POST.get('action')
if image_id and action:
try:
image = Image.objects.get(id=image_id)
if action == 'like':
image.users_like.add(request.user)
else:
image.users_like.remove(request.user)
return JsonResponse({'status':'ok'})
except:
pass
return JsonResponse({'status':'ko'})
def image_detail(request, id, slug):
image = get_object_or_404(Image, id=id, slug=slug)
return render(request,
'images/image/detail.html',
{'section': 'images',
'image': image})
In base.html :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script>
<script>
var csrftoken = $.cookie('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);
}
}
});
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>
And finnaly in the detail.html :
{% extends "base.html" %}
{% block title %}{{ image.title }}{% endblock %}
{% block content %}
...
{% with total_likes=image.users_like.count users_like=image.users_like.all %}
<div class="image-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button">
{% if request.user not in users_like %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
{{ image.description|linebreaks }}
</div>
<p> Image liked by :</p>
<div class="image-likes">
{% for user in image.users_like.all %}
<div>
<p>{{ user.last_name }}</p>
</div>
{% empty %}
Nobody likes this image yet.
{% endfor %}
</div>
{% endwith %}
{% endblock %}
{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post('{% url "images:like" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');
// toggle data-action
$('a.like').data('action', previous_action == 'like' ?
'unlike' : 'like');
// toggle link text
$('a.like').text(previous_action == 'like' ? 'Unlike' :
'Like');// update total likes
var previous_likes = parseInt($('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ?
previous_likes + 1 : previous_likes - 1);
}
}
);
});
{% endblock %}
While I mostly understand the code itself, I need help understanding in what orders the requests, the callback functions and everything else is executed ... something like : ,users clicks the like button, that information is passed to the server , it is being manipulated, data-base modified , sent back, the page changes ...
Tell me if any extra code ( models, urls etc. ) is needed. Could't post everything.

Add Like button with Django + Ajax

Hi I create my first project like stackoverflow(question-answer). I used this guid from Tango with Django http://www.tangowithdjango.com/book17/chapters/ajax.html to add like button with ajax. And nothing hapened. Don't see any request in console. I'm noob in Django, and it's my first encounter with jquery.
apps/questions/models:
class Answer(models.Model):
text = models.TextField()
date = models.DateTimeField(default=datetime.datetime.now)
likes = models.IntegerField(default=0)
resolve = models.IntegerField(default=0)
author = models.ForeignKey(CustomUser)
question = models.ForeignKey(Question)
apps/questions/views:
#login_required
def add_like(request):
ans_id = None
if request.method == 'GET':
ans_id = request.GET['answer_pk']
likes = 0
if ans_id:
ans = Answer.objects.get(id=(int(ans_id)))
if ans:
likes = ans.likes + 1
ans.likes = likes
ans.save()
return HttpResponse(likes)
apps/questions/ulrs:
url:
url(r'add_like/$', views.add_like, name='add_like'),
question.html:
{% for answer in answers %}
<div class="container-fluid no-padding">
{{ answer.text }}
</div>
<div class="container-fluid author-question">
<p>posted: {{ answer.date.day|stringformat:"02d" }}.{{ answer.date.month|stringformat:"02d"}}.{{ answer.date.year}}</p>
<p>by: {{ answer.author.username }}</p>
</div>
{% if user.is_authenticated %}
<button class="btn btn-default" type="button" id="likes" data-ansid="{{ answer.id }}">
like | <strong id="like_count">{{ answer.likes }}</strong>
</button>
{% endif %}
js/ajax.js:
$('#likes').click(function(){
var ansid;
ansid = $(this).attr("data-ansid");
$.get('/questions/add_like/', {answer_id: ansid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
Since you are creating buttons in a for loop, and naming them the same way, you have multiple elements on the page with the same id. Because of this you get unpredictable results. You should either give each button its own id, or change the jQuery selector to select the buttons based on the appropriate class.
For example, you could have:
{% for answer in answers %}
<div class="container-fluid no-padding">
{{ answer.text }}
</div>
<div class="container-fluid author-question">
<p>posted: {{ answer.date.day|stringformat:"02d" }}.{{ answer.date.month|stringformat:"02d"}}.{{ answer.date.year}}</p>
<p>by: {{ answer.author.username }}</p>
</div>
{% if user.is_authenticated %}
<button class="btn btn-default likes-button" type="button" data-ansid="{{ answer.id }}">
like | <strong id="like_count">{{ answer.likes }}</strong>
</button>
{% endif %}
{% endfor %}
And then for the javascript
$('.likes-button').click(function(){
var ansid;
ansid = $(this).attr("data-ansid");
$.get('/questions/add_like/', {answer_id: ansid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});

Categories

Resources