I am trying to make an AJAX call in my view using registerJS
.
My code is the following:
<?php $this->registerJs("
$(document).on('click','.btn-block',function(){
var id = $(this).parents('.user-tr').attr('id');
$.ajax({
url: "Yii::$app->request->baseUrl . 'admin/block-users'",
type: 'POST',
dataType: 'json',
data: {id : id,_csrf : "Yii::$app->request->getCsrfToken()"},
success: function (data) {
console.log(data);
},
});
})"); ?>
I want the URL to be the actionBlockUsers
method of AdminController
, but I am getting an error:
syntax error, unexpected 'Yii' (T_STRING), expecting ',' or ')'
The error is on this line:
url: "Yii::$app->request->baseUrl . 'admin/block-users'",
This is how my back-end function looks like:
public function actionBlockUsers()
{
if (Yii::$app->request->isAjax) {
//$data = Yii::$app->request->post();
print('success');
}
}
How can I fix this?
UPDATE
I changed the code to this as @Bizley suggested:
$this->registerJs("
$(document).on('click','.btn-block',function(){
var id = $(this).parents('.user-tr').attr('id');
$.ajax({
url: '" . Yii::$app->request->baseUrl . "admin/block-users',
type: 'POST',
dataType: 'json',
data: {id : id,_csrf : " . Yii::$app->request->getCsrfToken() . "},
success: function (data) {
console.log(data);
},
});
})");
The problem now is that I still can't send a request to my back end. How can I send the request?