Ajax request from js file to yii2 controller function

function facebookAuth() { $.ajax({ url: 'index.php?r=account/fbauthorize', type: 'GET' }); } 

this is a simple function that I wrote just to call a function in the controller, the GET type works fine, but the POST does not. give me this error "Bad request" (No. 400): "Unable to verify the sending of your data."

this has something to do with CSRF validation in yii2, but I can't solve it.

0
source share
3 answers

There are two important steps:

1) Register the js file as follows:

 $this->registerJsFile(Yii::$app->homeUrl . 'js/test.js', [JqueryAsset::className()]); 

2) In an ajax request, you need to send the following value along with the data:

 yii.getCsrfParam(): yii.getCsrfToken() 

CSRF is a security feature that can be disabled in the controller, but is not recommended.

+4
source

add two lines to your code

 contentType: "application/json; charset=utf-8", dataType: "json", 

it will be

 $.ajax({ url: 'index.php?r=account/fbauthorize', type: 'GET', contentType: "application/json; charset=utf-8", dataType: "json", }); 


Enjoy :)
0
source

Remember to set the correct access method.

 public function behaviors() { return [ 'verbs' => [ 'class' => \yii\filters\VerbFilter::className(), 'actions' => [ 'fbauthorize' => ['post'], ], ], ]; } 

http://www.yiiframework.com/doc-2.0/yii-filters-verbfilter.html

0
source

All Articles