I tried use answers about yii and ajax but not finded working examle. My script in yii2 bacis views/site/about.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl . '/controllers/SiteController/sample' ?>',
type: 'post',
data: {
searchname: 10,
searchby: 25,
_csrf: '<?= Yii::$app->request->getCsrfToken() ?>'
},
success: function (data) {
console.log(data.search);
console.log(data.code);
}
});
}
</script>
My function in SiteController:
public function actionSample() {
if (Yii::$app->request->isAjax) {
$search = "some-string";
$code = 20;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => $code,
];
}
}
I see post from ajax in browser OK.
POST http://localhost/web/controllers/SiteController/sample
200 OK
But conroller not answer . I get: "undefined".
May be problems with url? But I tried other:
Yii::$app->request->baseUrl . '/controllers/sample
. It didnt work too(