I have a button that must call my js function, but nothing happens when i do (there is no get requests)
My HTML:
<button type="button" id="checker" id="button{{answer.id}}" onclick="mark_as_correct({{answer.id}});">
</button>
My JS function:
function mark_as_correct(qid) {
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: 'url answerajaxcorrect',
type: 'post',
data: {id: qid},
success: function(data) {
document.getElementById('correct' + qid).innerHTML = "Correct!"
var button = document.getElementById('button' + qid)
button.parentNode.removeChild(button)
},
failure: function(data) {
alert('error')
}
})
}
I do include my js to template:
{% load static %}
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
And there is how my view looks like:
@login_required
def correct_ajax(request):
qid = int(request.POST.get("id"))
answer = get_object_or_404(Answer, id=qid)
if answer.author == request.user:
answer.is_correct = True
answer.save()
return JsonResponse({
"is_correct": True,
})
else:
return JsonResponse({
"is_correct": False,
})
I am new to js and django, so it is hard for me to understand the source of my problem, please help.