I am very new to AJAX and I made a simple test to see if I can get AJAX working.
If I press the like button, the server should increment 1 like and respond with the latest like count by alerting the user.
Now, I get an alert saying 'error'. It is now raising a 404
Looks like AJAX request has failed. Why is this happening?
index.html (partial)
<div>
{{ cmt.body }}<br/>
<strong>
<span class="like_count" style="color:green">{{cmt.likes}}</span>
<button type="button" class="like_btn" data-cmt_id="{{ cmt.id }}">Like</button>
</strong>
</div>
views.py
def update_like(request):
if request.is_ajax():
try:
cmt = Comment.objects.get(pk=int(request.POST['cmid']))
cmt.likes += 1
cmt.save()
except KeyError:
return HttpResponse('Error')
return HttpResponse(cmt.likes)
default.js (imported in base.html which index.html extends)
$(document).ready(function(){
$('.like_btn').on('click', function(){
var comment = $(this).attr('data-cmt_id');
$.ajax({
url: '/comment/update_like',
type: "POST",
data: {
cmid: comment
},
success: function(data){
alert("!!"+data);
},
error: function(){
alert('error');
}
});
})
});
Addition:::
urls.py
urlpatterns = patterns('',
(r'^$', index),
url(r'^admin/', include(admin.site.urls)),
url(r'^comment/update_like/$', update_like)
)
Ok, I finally managed to fix this issue.
First of all thanks to mrcrgl. I looked around for a debug console that gave me detailed information and turns out IE network tab provides extensive detail :)
The initial problem was identified by looking at response body which was a error page for not putting a '/' at the end of the js url.
It should have been
url: '/comment/update_like/'
not,
url: '/comment/update_like'
After this, I got a 403 Forbidden. Quick google search gave me this
403 Forbidden error when making an ajax Post request in Django framework
Turns out it was the missing CSRF token that was causing problems. I just added
@csrf_exempt
on top of my update_like view and it works find now ;)
So changing the URL worked as it was a post ajax request, but either change it to GET request in ajax or if you want to use POST request it is a good notion to pass csrf token.
So if you want the csrf token to be there, which is good for POST ajax methods, then you can remove the @csrf tag and in you java script write a method to get csrf token as suggested here
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax