I want to add the following functionality to a site but need Jquery to change the following to unfollow and vice-versa. Everything seems fine but it's not working. (All the links to jquery work perfectly and load)
Jquery for the functionality
$('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "user_follow" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if(data['status'] == 'ok' ){var previous_action == $('a.follow').data('action');
console.log(previous_action);
// toggle data_action
$('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow');
// toggle link text
$('a.follow').text(previous_action =='follow' ? 'Unfollow' : 'Follow');
// update followers
var previous_followers = parseInt($('span.count .total').text());
$('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1);
}
}
)
});
HTML
{% with total_followers=user.followers.count %}
<span class="count">
<span class="total">{{ total_followers }}</span>
follower{{ total_followers|pluralize }}
</span>
<a href="" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow btn">
{% if request.user not in user.followers.all %}
Follow
{% else %}
Unfollow
{% endif %}
</a>
{% endwith %}
view for on jquery request
@login_required
def user_follow(request):
user_id = request.POST.get('id')
action = request.POST.get('action')
if user_id and action:
try:
user = User.objects.get(id=user_id)
if action == 'follow':
Contact.objects.get_or_create(
user_from=request.user,
user_to=user
)
else:
Contact.objects.filter(user_from=request.user, user_to=user).delete()
return JsonResponse({'status': 'ok'})
except User.DoesNotExist:
return JsonResponse({'status': 'error'})
return JsonResponse({'status': 'error'})
Last note There is a jquery for the like button above the followers' jquery object don't know if its presence has any effect