0

I am trying to send a POST request from javascript to views.py using AJAX. However, I am getting a 403 Error stating that csrf token is not present.

In order to resolve this issue I followed this link and included the function in my javascript. However, I am confused as to what the next step should be.

Any assistance will be appreciated. Thanks!

1 Answer 1

2

Simply add somewhere in your template:

{% csrf_token %}

Then in your js file should be smth like this:

var csrf_token;

var sendSomeAjax = function(target) {
    var requestUrl = $(target).data('url');

    return $.ajax({
        url: requestUrl,
        type: 'post',
        headers: {
            'X-CSRFToken': csrf_token
        },
        dataType: 'json'
        // also you can pass some 'data: ' here
    })
};

$(function() {
    csrf_token = $('input[name="csrfmiddlewaretoken"]').val();

    var target = $('.someSelectorWhereYouHavePassedDataUrlToYourView');
    // for example in your template <a href="#" data-url="{% url 'app_url_namespace:view_url_name' %}"</a>

    sendSomeAjax(target).success(function(data) {
        // do smth with data =)
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks madzohan. For me just changing the key of the csrf token from 'csrftoken' to 'csrfmiddlewaretoken' did the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.