10

Is the data:.. line below correct? I want to post the form data AND csrf token to a Django view function.

$('#file-upload').on('change', function () {
    var currentpath = window.location.pathname;
    var formData = new FormData($('form')[0]);
    $.ajax({
            url: currentpath,  //server script to process data
            type: 'POST',
            data: {formData, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            cache: false,
            contentType: false,
            processData: false
        });
});
Musa
  • 96,336
  • 17
  • 118
  • 137
Philip007
  • 3,190
  • 7
  • 46
  • 71
  • 1
    I should point out that `{{ csrf_token }}` will only work if this code appears on the body of the template. If it's inside an imported JS file. It wont work. – Bibhas Debnath May 26 '13 at 20:52
  • There is a workaround to that as well. Define a `
    {{ csrf_token }}
    ` in your template file. In your imported JS file you can add the token to the FormData object as `formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');`
    – shaktimaan Jan 31 '14 at 18:42

1 Answers1

21

You have to add your parameters to the FormData object (using append) and as always pass the formdata object alone as the data property.

$('#id_image').on('change', function () {
    var currentpath = window.location.pathname;
    var formData = new FormData($('form')[0]);
    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
            url: currentpath,  //server script to process data
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
});
Musa
  • 96,336
  • 17
  • 118
  • 137
  • @Philip007 my bad I used a `:` instead of a `,` to separate the params in append (too much rpg). See update. – Musa May 26 '13 at 17:52
  • Thanks, you saved my day – medoingthings Nov 03 '16 at 07:19
  • 3
    Doesn't work for me. I still get the 403 because of the missing token. If I comment out "processData: false" then I get `TypeError: 'append' called on an object that does not implement interface FormData.` – M46 Jan 18 '18 at 08:55