Answer the question
In order to leave comments, you need to log in
How to make a link with parameters for Ajax?
I want to get data from the controller when clicking on the link without refreshing the page, that is, with Ajax
<?= Html::a('подробнее', ['/site/default/news', 'id'=>(int)$item->id], [
'class' => 'btn btn-small',
'data' => [
'data-method' => 'post',
],
]) ?>
<?php
$js = "$('.btn').on('click', function()
{
$.post(
\"/site/default/news\", {
id : тут надо передать айди новости
},
)
}
)";
$this->registerJs($js, $this::POS_READY);
?>
Answer the question
In order to leave comments, you need to log in
Depending on which version of Yii.
In version 1 look at CHtml::ajaxSubmitButton.
In version 2 I can not find something similar, maybe someone will correct me.
But you can do it in a similar way that you wrote, just remember to cancel the click action on the link, for example:
$('.btn').on('click', function(e){
e.preventDefault();
/** код */
});
$.post(
"/site/default/news",
{id : /** id новости */},
function(data){
$('#content').html(data);
}
);
For the second day I've been fighting with this Ajax, this is what happened:
There is a block that, when you click on the link, opens with a brief description of the news, and below there is a button for more details.
<td>
<?= Html::a($item->title, 'javascript:show("newsid", ' . (int)$item->link . ')') ?>
</td>
<tr>
<td>
<div style="display:none" id="newsid_<?= (int)$item->link ?>">
<?= $item->description ?>
<?= Html::a('подробнее', ['/site/default/footballnews', 'id'=>(int)$item->link], [
'id' => 'link_fnews',
'class' => 'btn btn-small',
'data' => [
'data-method' => 'post',
],
]) ?>
</div>
</td>
<?php
$js = "$('#link_fnews').on('click', function(e)
{
e.preventDefault();
var link = $(this).attr('href');
var id = link.split('?id='); // парсю строку и получаю чистый ID новости
$('#link_fnews').html('<i class=\"fa fa-spinner fa-pulse\"></i>'); // здесь гружу анимацию(loading)
$.post
(
link,
function(data)
{
$('#link_fnews').html(''); // убираю анимацию
$('#newsid_'+id[1]).append(data) // грузим новость в блок с айди новостью
}
);
}
)";
$this->registerJs($js, $this::POS_READY);
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question