Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: post FormData AND csrf token together

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
        });
});
like image 616
Philip007 Avatar asked May 26 '13 17:05

Philip007


1 Answers

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
        });
});
like image 69
Musa Avatar answered Oct 18 '22 01:10

Musa