I try to send an AJAX GET request from a sub domain to a main domain. Below is my AJAX code.
$.get('http://my-yii2-website.com/controller/test-method',
{data: '1')},
function(returnedData){
alert(returnedData);
},
'json'
);
This above code resides in the sub domain. In the main domain I have the controller and action method that looks like following.
public function behaviors()
{
$subDomain = 'http://subdomain.my-yii2-website.com';
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => [$subDomain, ],
'Access-Control-Request-Method' => ['GET', ],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => null,
'Access-Control-Max-Age' => 3600,
],
],
];
}
public function actionTestMethod()
{
$request = Yii::$app->request;
if($request->isAjax)
{
return json_encode('OK!');
}
else
{
return json_encode('ERROR');
}
}
It does work. But due to the if-statement in the actionTestMethod(), it does not see the request as an AJAX request. It returns the predefined 'ERROR' message. I am working with Yii framework 2.0.