M
M
Maxim Timofeev2016-06-06 16:37:02
JavaScript
Maxim Timofeev, 2016-06-06 16:37:02

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;

Here is the whole action:
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;
    }

Should I do setStatusCode or just return json, and then parse the error in js if else or not and display an error?
I display errors through the alertify script.
All ideas, links and poking your nose in kaku - great respect.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mitaichik, 2016-06-06
@webinar

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 question

Ask a Question

731 491 924 answers to any question