I have a button that increments an upvote. I'd like to make the button with ajax so it does not reload the page. I am trying to follow this, but my button uses <a type="button">
. Is this an issue with my html ?
views.py
@login_required
def upvote(request):
recommendation_id = None
if request.method == 'GET':
#recommendation_id = request.GET['recommendation_id']
recommendation_id = request.POST.get('recommendation_id', False)
upvotes = 0
if recommendation_id:
recommendation = coremodels.Recommendation.objects.get(id=int(recommendation_id))
user = request.user
recommendation.votes.up(user)
upvotes = recommendation.votes.count()
return HttpResponse(upvotes)
urls.py
url(r'^upvote/', coreviews.upvote, name='upvote'),
html:
<a type="button" id="upvotes" data-recommendation="{{ recommendation.id }}" href="{% url 'upvote' %}" class="btn btn-primary pull-right"><span class="glyphicon glyphicon-thumbs-up"></span>Upvote</a>
ajax.js
$('#upvotes').click(function(event){
event.preventDefault();
var recommendation = $(this).attr("data-recommendation");
$.get('/upvote/', {recommendation_id: recommendation}, function(data){
$('#upvotes').hide();
});
});
Current Error:
The page is still reloading on click. The views.py request.GET['recommendation_id']
is unsuccessful.