Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ajax call in yii2?

Tags:

php

yii2

In yii version 1.14 we used

CHtml::ajaxlink

for ajax call what about in yii2?

like image 362
mohi Avatar asked Jun 13 '14 07:06

mohi


2 Answers

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;",
                ]);
like image 133
Dency G B Avatar answered Oct 14 '22 02:10

Dency G B


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
like image 36
NinjaCat Avatar answered Oct 14 '22 03:10

NinjaCat