skip to Main Content

I’m using the following code as recommended by the documentation:

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }
            $("#formTabla").submit(function(event){
                event.preventDefault();
                var formData = new FormData(this);
                $.ajax({
                    beforeSend: function(xhr, settings) {
                        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                            xhr.setRequestHeader("X-CSRFToken", csrftoken);
                        }
                    }
                    url : "{% url 'submit' %}",
                    type: "POST",
                    processData: false,
                    contentType: false,
                    data: {
                        "checkboxes": formData,
                        "datos": todosDatos
                    },
                    success: function (respuesta){
                    }
                });
            });

I’m getting the error :

 "Uncaught ReferenceError: csrftoken is not defined".

I understand why this happens, but I have no idea how to solve it. How and where am I supposed to define crsftoken?

2

Answers


  1. You can use ajaxSend() for this

    $(document).ajaxSend(function(event, xhr, settings){
        if (!csrfSafeMethod(settings.type)) {
           xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });
    
    Login or Signup to reply.
  2. the variable is not defined anywhere, first you need to obtain csrf_token:

    import Cookies from 'cookies-js'
    let csrftoken  = Cookies.get('csrftoken')
    
    

    then set the variable in request header.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search