Search code examples
jqueryajaxcodeignitercsrfdropzone.js

codeigniter dropzone ajax upload with csrf


i'm using dropZone JS jquery plugin to upload images using codeigniter , in form there is a reset button for the form , when user upload image he can reset the form for new upload but after reset when upload it show a message

The action you have requested is not allowed.

by the way first upload success after that it fails with that message note that i'm using the csrf protection

here is the init code for dropzone

 $(".dropzone").dropzone({
        url: "Images/up",
        maxFiles: 1,
        maxFilesize: 10, 
        acceptedFiles: 'image/*',
        autoProcessQueue: false,
        autoDiscover: false,
        params: {csrf_token: $.cookie("csrf_value")},
        init: function () {
            this.on("addedfile", function (file) {
                $('#init_empty_msg').addClass('hidden');
            });
        }

    });

Solution

  • You can use $.ajaxPrefilter() before you all ajax and add to all your ajax in data option csrf token. After this you make your ajax requests typicaly without declaration in data array csrf data and

    // for CI 3.0.4
    data: {"<?= $this->security->get_csrf_token_name() ?>": "<?= $this->security->get_csrf_hash() ?>"}