Multiple ajax calls with csrf validation

I have a problem with csrf validation. What happens is that in a view I make two calls via ajax, one associated with a form (activeform/validate) and another associated with uploading files. The problem occurs if I make a call to upload a file, after the form one, this causes the token to be invalid. How can I make multiple ajax calls form one view: validate form, upload files ?

I would appreciate if someone can help me.

Thanks in advance.

Are you sending the csrf token with your ajax request? ActiveForm puts a hidden field with this value so you don’t need to, however if it’s a regular ajax call you will need to do this yourself.





jQuery.ajax({

    Your_other_settings,

    data: {

        data: 'your data',

        _csrf: yii.getCsrfToken()

    }

});


or


$this->registerJs('jQuery.ajax({

    Your_other_settings,

    data: {

        data: "your data",

        _csrf: '.\Yii::$app->request->csrfToken.'

    }

});');



Please use


yii\web\Response::enableCsrfCookie

See my answer here https://laracasts.com/discuss/channels/laravel/need-some-advice-on-saving-a-ajax-form-data-into-l5 not yii but laravel, but works the same.

Frameworks are so specialized, it’s much easier just getting the token in a normal fashion, see where I have the




$post._token = document.getElementsByName("_token")[0].value



I have never had trouble in Yii or laravel or cake just using normal jquery ajax techniques rather than silly specialized techniques in-built in the frameworks.

Sometimes these frameworks get too specialized.

And for multi calls, send a new token with each, learn how to do your own csrf routines and not depend on in-built stuff, which usually gets in the way.