Onclick button does not call js function in django

Viewed 993

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.

1 Answers

onclick="mark_as_correct({{answer.id}});"

The function reference you pass to onclick needs to be able to take an event parameter. When you point to a function with assigned argument to onclick, the browser will execute the function at read time, and assign the result of that function to onclick.

In your case, you can just create an anonymous function to do the trick:

<button type="button" id="checker" id="button{{answer.id}}" onclick="function() { mark_as_correct({{answer.id}}) };">
Related