Stackaccount1
Stackaccount1

Reputation: 149

JQuery AJAX with django getting csrf error 403

Getting Error CSRF verification failed. Request aborted. Missing or Incorrect Token. I am new to JQuery not sure if it is contributing to my error. I think I am passing the request properly. Cookies are accepted and a simpler JQuery request worked earlier.

Views

def testcall(request):
    text = request.POST['text']
    if request.method == 'POST' and request.POST['action'] == 'start_function1':
        function1(text)
        response = text + "has been successful"
        return HttpResponse(response)
    if request.method == 'POST' and request.POST['action'] == 'start_function2':
        function2(text)
        response = text + "has been successful"
        return HttpResponse(response)

Template

<html>
<head>
    <title>Test Data</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
            jQuery(document).ready(function($){
            $('demo-form').on('submit', function(event){
                event.preventDefault();
                var text = document.getElementById('text-to-analyze').value;
                $.ajax({
                    url : '{{ 'my-ajax-testsub/' }}',
                    type : "POST",
                    data: {
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                        text: text,
                        action: 'start_function1'
                    },
                    success: function callback(response){
                           alert(response);
                           },
                    });
            })})
            jQuery(document).ready(function($){
            $('demo-form').on('submit', function(event){
                event.preventDefault();
                var text = document.getElementById('text-to-analyze').value;
                $.ajax({
                    url : '{{ 'my-ajax-testunsub/' }}',
                    type : "POST",
                    data: {
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                        text: text,
                        action: 'start_function2'
                    },
                    success: function callback(response){
                           alert(response);
                           },
                });
            })})
    </script>
</head>
<body>
    <form name="demo-form" method="POST" action="{% url 'home' %}">
        <p>Input field: <input type="text" id="text-to-analyze" value="[email protected]"></p><br>
        <button class="btn btn-success" name="start_function1">Function</button>
        <button class="btn btn-success" name="start_function2">Function</button>
    </form>
</body>
</html>

Upvotes: 1

Views: 219

Answers (1)

Safwan Samsudeen
Safwan Samsudeen

Reputation: 1707

This is not how you render the csrf_token, you must use {% csrf_token %}. So currently, it's sending the csrf_token as a blank.

But anyway, that doesn't matter. You must get the csrf_token from the HTML - after it's rendered. Because Django replaces {% csrf_token %} with a unique token (input actually), so it'll be incorrect anyway.

data: {
    csrfmiddlewaretoken: $($('input[name="csrfmiddlewaretoken"]').attr('value')),
    text: text,
    action: 'start_function1'
},

Even this may not work. You may need to set it as a header.

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Csrf-Token', token);
    }
});
[...]
    data: {
        csrfmiddlewaretoken: $($('input[name="csrfmiddlewaretoken"]').attr('value')),
        text: text,
        action: 'start_function1'
    },
[...]

Upvotes: 1

Related Questions