mohi
mohi

Reputation: 93

How to make ajax call in yii2?

In yii version 1.14 we used

CHtml::ajaxlink

for ajax call what about in yii2?

Upvotes: 8

Views: 43288

Answers (4)

user7699448
user7699448

Reputation:

$.get( "' . Url::toRoute('controller/action') . '", { item: $("#idoffield").val()} ) /* to send the parameter to controller*/
                        .done(function( data )
                            {
                                 $( "#lists" ).html( data );
                                    }) 

and give lists id for div

<div id="lists"></div>

for more visit https://youtu.be/it5oNLDNU44

Upvotes: 0

Pushparaj Yuvaraj
Pushparaj Yuvaraj

Reputation: 11

<?=yii\helpers\Url::toRoute("site/signup")?>

Upvotes: -3

Dency G B
Dency G B

Reputation: 8146

You can make an ajax link like

 Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
    'onclick'=>"$('#close').dialog('open');//for jui dialog in my page
     $.ajax({
    type     :'POST',
    cache    : false,
    url  : 'controller/action',
    success  : function(response) {
        $('#close').html(response);
    }
    });return false;",
                ]);

Upvotes: 19

NinjaCat
NinjaCat

Reputation: 10194

From: http://www.yiiframework.com/wiki/665/overcoming-removal-of-client-helpers-e-g-ajaxlink-and-clientscript-in-yii-2-0/

You can easily create and combine all such client helpers for your need into separate JS files. Use the new AssetBundle and AssetManager functionality with the View object in Yii2, to manage these assets and how they are loaded.

Alternatively, inline assets (JS/CSS) can be registered at runtime from within the View. For example you can clearly simulate the ajaxLink feature using a inline javascript. Its however recommended if you can merge where possible, client code (JS/CSS) into separate JS/CSS files and loaded through the AssetBundle. Note there is no more need of a CClientScript anymore:

$script = <<< JS
$('#el').on('click', function(e) {
    $.ajax({
       url: '/path/to/action',
       data: {id: '<id>', 'other': '<other>'},
       success: function(data) {
           // process data
       }
    });
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default), 
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END

Upvotes: 9

Related Questions