Question

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

it is a simple function i wrote just to invoke the function in the controller, the GET type works fine, but the POST does not. give me this error "Bad Request (#400): Unable to verify your data submission."

it is something to do with CSRF validation in yii2, but i can't solve it.

Was it helpful?

Solution

There are two important steps:

1) Register your js file as follows:

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

2) In ajax request you need to post following value along with data:

yii.getCsrfParam(): yii.getCsrfToken()

CSRF is a security feature which can be disabled in controller, but it is not recommended.

OTHER TIPS

add this two line to your code

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

this will be

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


Enjoy :)

Make sure to set the right 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top