Ajax Post with csrf token

linkaiyi
Follow

Ajax Post in django template must use form data type to post, otherwise django cannot recognize csrf_token and report CSRF Forbidden.

var send_data = new FormData();
        send_data.append("object_id", {{ object_id }});
        send_data.append("object_type", '{{ object_type }}');
        send_data.append("csrfmiddlewaretoken", '{{ csrf_token }}');
        $.ajax({
            type: 'POST',
            url: '/course/send_certificate/',
            data: send_data,
            processData: false,
            contentType: false,
            // dataType: "json",
            success: function (data, textStatus, jqXHR) {
                $(e.currentTarget).find('div[id="modal-body"]').html(data);
            }
        })
function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
Object has 0 attachments

Was this article helpful?

This article is viewed 10 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support