Answer the question
In order to leave comments, you need to log in
Is it correct to form errors for json request like this?
There is an action that only accepts ajax. Checks if there is an entry with this id and whether there is access to delete an entry with this id. Everything works, but I'm not sure if this part is correct:
Yii::$app->response->setStatusCode('401',Yii::t('text','You are not allowed to perform this operation'));
return false;
public function actionDeleteComment($id)
{
Yii::$app->response->format = Response::FORMAT_JSON;
if($model = Comment::findOne($id)) {
if (Yii::$app->user->can('updateComment', ['comment' => $model])) {
$model->delete();
return ['status'=>'success','message'=>Yii::t('text','Your post deleted successfully')];
}else{
Yii::$app->response->setStatusCode('401',Yii::t('text','You are not allowed to perform this operation'));
return false;
}
}
Yii::$app->response->setStatusCode('404',Yii::t('text','An error occurred'));
return false;
}
Answer the question
In order to leave comments, you need to log in
Return HTTP status - (this is what setStatusCode does) - yes, it is necessary, this is correct, and it will be more convenient to write code from the js side. Your doubts are most likely due to the fact that few people do this - but this is purely due to the inexperience of those who do not.
Also, if you have json, I advise you to read everything about the rest from the yii documentation ( https://github.com/yiisoft/yii2/tree/master/docs/g... - a lot of interesting things are written there, something is already in the framework prepared for it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question