My js
script works a bit strange:
<?php use app\models\User; use yii\helpers\Html; use app\components\PeopleWidget; use yii\helpers\Url; /** * @var User $peopleArr * @var PeopleWidget $context */ ?> <?php foreach ($peopleArr as $people): ?> <?php echo Html::a($people->getAttribute('name'), Url::to(['/user/index', 'id' => $people->getAttribute('nick_name')]));?> <?php echo $people->getAttribute('nick_name');?> <?php echo Html::button('Сообщение', ['id' => $people->getId(), 'class' => 'mail-to'])?> <?php echo Html::button($context->isFriend($people->getId()) ? PeopleWidget::REMOVE_FROM_FRIEND : PeopleWidget::ADD_TO_FRIEND, ['id' => PeopleWidget::REMOVE_FROM_FRIEND ? $context->getFriendId($people->getId()) : $people->getId(), 'class' => 'action-to-user']);?> <?php endforeach;?> <?php $removeText = PeopleWidget::REMOVE_FROM_FRIEND; $addText = PeopleWidget::ADD_TO_FRIEND; $checkFriend = <<< JS var removeText = "$removeText"; var addText = "$addText"; $('.action-to-user').click(function() { if ($(this).text() == removeText) { $.ajax('/user/delete-friend/', { type: 'post', data: 'id-friend=' + this.id + '&is-people=' + true, success: function (response) { $(('#'+response)).text(addText); }, error: function() { alert('error'); } }); } if ($(this).text() == addText) { $.ajax('/user/add-friend/', { type: 'post', data: 'id-friend=' + this.id, success: function(response) { alert(response); }, error: function() { alert('error'); } }); } }); JS; $this->registerJs($checkFriend, \yii\web\View::POS_READY); ?>
When the first condition is met, the button id is transmitted correctly and the action is performed correctly!
But when the second condition is met, nothing is transmitted! That is, an empty string is passed to the controller action!
I tried different options, for example, asking the button just one id
, for example 5 - the result does not change!
But when to do so:
if ($(this).text() == addText) { $.ajax('/user/add-friend/', { type: 'post', data: 'id-friend=' + 5, success: function(response) { alert(response); }, error: function() { alert('error'); }
Everything works correctly! What did I miss? Or maybe somewhere wrong?
I would be grateful for the tip))
var text = $(this).text; var id = $(this).id;
var text = $(this).text; var id = $(this).id;
. Although I agree with the previous commentator, it is possible that the button with the text addText has no id parameter. - alexoander