I'm currently working on a Django app that features user posts, and I'm in the process of implementing a 'like' / voting system. Initially, I set up this functionality using complete page refreshes combined with a redirect after the vote was made to update the like count. However, I recently learned about ajax and how it enables partial page updates without the need for a full reload.
let up_vote = document.getElementById("up-vote").addEventListener('click', () => {
console.log("clicked");
let xhr = new XMLHttpRequest();
xhr.open('GET', "{% url 'up-vote' %}", true);
console.log(xhr);
xhr.onload = () => {
console.log("inside");
};
console.log("outside");
});
My current javascript code functions as described above. When clicking "up-vote," the console logs "clicked" along with the xhr object. However, the onload
event seems to be skipping as "inside" is never printed, instead jumping straight to "outside."
I suspect that the problem lies with the URL path, but I'm unsure how to rectify it. The file structure of my app is organized as follows:
app
|-static/app
|-scripts/*this js file*/
|-images
|-styles
|-templates/app
|-html files
|-views.py *which handles the request*
|-urls.py
Within urls.py,
urlpatterns = [
...
path('post/<int:pk>/up/', up_vote, name='up-vote'),
...
]
and views.py contains the following:
@login_required()
def up_vote(request, pk):
print("HI")
obj = get_object_or_404(Post, pk=pk)
uid = request.user.id
if not obj.votes.exists(uid):
obj.votes.up(uid)
data = {
'votes': obj.votes.count()
}
return JsonResponse(data)
Any assistance or guidance would be greatly appreciated :)
p.s. I also attempted using xhr.onreadystate, which led me to believe there might be an issue with the URL path.