Answer the question
In order to leave comments, you need to log in
How to connect an action with ajax in Yii2 so that this action can be reused?
Hi, I've just started learning Yii and I'm having a problem.
Problem: in the user profile there are conditionally 10 blocks with his data, they are edited via ajax, after editing the result is immediately displayed, also via ajax, that is, you need to load the view 2 times.
Question: What to do with the controller so as not to write an action for each block? How can you make it so that there is one action that would be universal for all blocks and decide on its own what to do with a particular block?
Answer the question
In order to leave comments, you need to log in
Whoa, what are you doing? CRUD generated from gii is quite suitable for you, with ajax post the form to actionUpdate (), and in it from the standard add only the ajax check line after saving the model in order to return not the full view, but the json response.
In general, look at how standard ajax validation is done in Yii, in addition to validation, insert a line for saving the model.
Here in the documentation:
www.yiiframework.com/doc-2.0/guide-structure-contr...
And here is the description of the class that needs to be inherited
www.yiiframework.com/doc-2.0/yii-base-action.html
Try to reproduce this design. I do it through a function, because the abundance of pjax blocks interferes with the correct processing of jquery events. function is easier.
action should return an array for you, which you will need to process in the response (respond).
Action example:
public function actionTest(){
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out['error'] = 0;
$out['html'] = 'html block';
$out['per'] = 1;
return $out;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="blocks">
<div class="block" data-attr='1'>
<a href="" onclick="clickme(this); return false;">click me</a>
</div>
<div class="block" data-attr='2'>
<a href="" onclick="clickme(this); return false;">click me</a>
</div>
<div class="block" data-attr='3'>
<a href="" onclick="clickme(this); return false;">click me</a>
</div>
</div>
</body>
</html>
<script>
function clickme(obj) {
alert($(obj).parents('.block').attr('data-attr'));
var id = $(obj).parents('.block').attr('data-attr');
$.post(
"/url",
{
id: id
},
function(respond) {
if (respond['error'] == '0') { //если ошибки нет то продолжаем
} else if (respond['error'] == '1') {
alert(respond['text']);
}
}
);
}
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question