I need to implement AJAX and its working fine. However, I am having problem in applying ajax to each instance of a model. It's just being applied on the top Object and applying ajax call on the same page. For remaining objects, when I click on the link its directing me to new page and showing me JSON objects which I dont want.
Views.py
def upvote(request, post_id):
if request.method == "POST":
p = get_object_or_404(Post, pk=post_id)
p.upvote += 1
p.save()
return JsonResponse({'count':p.upvote })
if request.method == "GET":
p = get_object_or_404(Post, pk=post_id)
p.upvote += 1
p.save()
data = {
'count' : p.upvote,
}
return JsonResponse({'count': p.upvote})
Urls.py
url(r'^(?P<post_id>[0-9]+)/upvote/$', views.upvote, name='upvote-detail'),
Views.html
<script>
$(function(){
$('#up_vote').click(function(e) {
e.preventDefault();
window.alert("hello");
console.log("hello");
$.ajax({
url: $(this).attr('href'),
type :'get' ,
success : function (data){
// alert('success');
$('#upvote_count').html(data.count);
},
failure : function (data){
alert('failure') ;
}
}) ; // ajax call
}); // upvote link call
</script>
<div id="columns">
{% for post in object_list %}
<div class="pin">
<a href="/posts/{{ post.id }}/">
<img src= "/static/media/{{post.image}}" />
</a>
<p>
{{post.description}}
(<a href="{% url "post-edit" pk=post.id %}">edit</a>)
</p>
<div style="float:left">
<a href='{% url 'upvote-detail' post.id %}' id='up_vote'>Up vote </a>
<span id='upvote_count'> {{ post.upvote }} </span>
</div>
<div style="float:right">
<a href='{% url 'downvote-detail' post.id %}' id='down_vote'> Down vote </a>
<span id='downvote_count'>{{post.downvote}}</span>
</div>
</div>
{% endfor %}
</div>
Here is my all the files. Currently AJAX call is working absolutely fine. Its just applying on the top (first) of object in for LOOP. For Remaining objects, when I click on link, it render me to new page. Could someone identify the problem? Thanks,