How can I, reload only grid-view on on change event of drop-down in Yii2?
I know that it can be done via pjax but not sure where and how to use the code.
I am using Ajax request for communicating with controller. Here is the ajax code:-
function loadGrid(level) {
alert(level);
$.ajax({
type: 'GET',
url: 'index.php?r=villagedata/level',
data: {level:level},
success: function(data)
{
alert("Success");
$.pjax({container: '#myview'});
}
});
}
I wan't my grid to reload when the Ajax Request returns success message.
Thank You.
Exactly, using Pjax.
use yii\grid\GridView;
use yii\widgets\Pjax;
<?php Pjax::begin(['id' => 'pjax-grid-view']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'...'
],
]); ?>
<?php Pjax::end(); ?>
and jQuery to detect drop down change.
If dropdown has "dropdown" id,
$('#dropdown').on('change', function(ev) {
$.pjax({container: '#pjax-grid-view'})
});
Try
$("#idyourgrid").yiiGridView("applyFilter");
Related
I'm new to CakePHP and ajax. I'm trying to figure out how to utilize AJAX to make dependent (chained) dropdown in CakePHP 3.8.0.
I'm making a few tables for example to learn how to build the chained dropdown menu. I have three tables models, chapters, userinputs. In the Userinputs table, I would to chapter to load based on model. Right now all models and all chapters are shown. This is how they're all connected.
how all three tables are connected
I've been looking at some examples online and tried to apply them into my code but nothing seems to be working. This is my add.ctp of my Userinputs table.
<div class="userinputs form large-9 medium-8 columns content">
<?= $this->Form->create($userinput, ['type' => 'file', 'class' => 'ajax_page']) ?>
<fieldset>
<legend><?= __('Add Userinput') ?><div class="ajax_loading_image"></legend>
<?php
echo $this->Form->control('model_id', ['options' => $models, 'empty' => true, 'id'=>'models']);
echo $this->Form->control('chapter_id', ['options' => $chapters, 'empty' => true, 'id'=>'chapters']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I also added this script at the end of add.ctp of Userinputs table
<script>
$("#models").on('change',function() {
var id = $(this).val();
$("#chapters").find('option').remove();
if (id) {
var dataString = 'id='+ id;
$.ajax({
dataType:'json',
type: "POST",
url: '<?php echo Router::url(array("controller" => "Userinputs", "action" => "getChapters")); ?>' ,
data: dataString,
cache: false,
success: function(html) {
//$("#loding1").hide();
$.each(html, function(key, value) {
//alert(key);
//alert(value);
//$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#chapters"));
});
}
});
}
});
</script>
In the controller of my Userinputs, I added a public function
public function getChapters()
{
$id = $this->request->data('id');
$chapters = $this->Chapters->find('all', [ 'conditions' => [ 'model_id' => $id ] ]);
echo json_encode($chapters);
}
Please take a look at my codes and please assist me on how to get this working properly. Any help is much appreciated.
I am trying to add a from with a CKeditor widget imbedded via an AJAX request. The request itself works fine and returns the general partial view as I want it. Except for the Ckeditor widget, a normal textbox is return instead.
When the item is added to the group and the page is reloaded, the same partialView is being rendered (in a foreach with all group-items) and this time the CKeditor is nicely in place.
Posted my controller, initialization of the CKeditor and Scipt with AJAX request below. (The CKeditor is inlcuded in the _ContentItemHtml view)
I have taken a look at this, but I cannot call any CKeditor functions from JS since it is loaded as a widget.
Controller Action
public function actionCreateHtml($contentitemgroupid)
{
$model = new ContentItemHtml();
if (isset(Yii::$app->request->post()['ContentItemHtml'])) {
$item = Yii::$app->request->post()['ContentItemHtml'];
$model->contentitemgroupid = $contentitemgroupid;
$model->title = $item['title'];
$model->body = $item['body'];
$model->save();
// return $this->redirect(['edit', 'id' => $model->contentitemgroupid]);
}
else
return $this->renderPartial('_ContentItemHtml', ['model' => $model]);
}
Active form in view:
echo $form->field($model, 'body')->widget(CKEditor::className(), [
'preset' => 'custom',
'clientOptions' => [
'height' => 200,
'toolbarGroups' => [
['name' => 'basicstyles', 'groups' => ['basicstyles', 'cleanup']],
['name' => 'paragraph', 'groups' => ['templates', 'list']],
['name' => 'mode']]
]])->label(false);
Script.js
$('#addNewContentItem').on('click', function (e) {
e.preventDefault();
var url = 'create-' + $('#itemSelector').val().toLowerCase() + '?contentitemgroupid=' + $('#itemSelector').attr('contentitemgroupid');
$.ajax({
type: 'POST',
url: url,
cache: false,
success: function(res) {
$('.contentItemsManager').append('<div class="ContentItemContainer row">' + res + '</div>');
AddSaveEventListener();
AddSaveMediafileEventListener();
AddRemoveEventListener();
}
});
});
Use renderAjax instead of renderPartial. From the docs:
[renderAjax] Renders a view in response to an AJAX request.
This method is similar to renderPartial() except that it will inject into the rendering result with JS/CSS scripts and files which are registered with the view. For this reason, you should use this method instead of renderPartial() to render a view to respond to an AJAX request.
I'm using Yii2's advanced template, and looking for a way to display a dialog with 'Please wait...' message while sending an login form to the server.
Here is my active form code:
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
]); ?>
<fieldset>
<?= $form->field($model, 'username', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('username'),
],
])->label(false); ?>
<?= $form->field($model, 'password', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('password'),
],
])->label(false)->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-lg btn-success btn-block', 'name' => 'login-button']) ?>
</fieldset>
<?php ActiveForm::end(); ?>
And my server side action:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
I'm successfully validating the inputs / sending the form, but need to display a dialog, so if the connection is slow the user will get an idea that the form is actually sending and needs more time to complete.
For ActiveForm you need to use according events. Currently it's managed with Javascript (see official upgrade info).
$('#myform').on('ajaxBeforeSend', function (event, jqXHR, settings) {
// Activate waiting label
}).on('ajaxComplete', function (event, jqXHR, textStatus) {
// Deactivate waiting label
});
Here is more detailed info about these two events.
ajaxBeforeSend:
ajaxBeforeSend event is triggered before sending an AJAX request for
AJAX-based validation.
The signature of the event handler should be:
function (event, jqXHR, settings)
where
event: an Event object.
jqXHR: a jqXHR object
settings: the settings for the AJAX request
ajaxComplete:
ajaxComplete event is triggered after completing an AJAX request for
AJAX-based validation. The signature of the event handler should be:
function (event, jqXHR, textStatus)
where
event: an Event object.
jqXHR: a jqXHR object
textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
Also check this extension, maybe it will be useful for this purpose.
Please use the following javascript solution to listen to 'before submit'
$('body').on('beforeSubmit', 'form#yourFormId', function() {
$('#loading').show(); //show the loading div
var form = $(this);
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
// do processing of data
$('#loading').hide(); //hide it
}
});
return false;
});
You will need to add a div with id loading and use suitable css for that
<div id='loading'> Loading ... </div>
Adding a maunal close button to this div is also recommended for cases with network fluctuations
I am new to CakePHP, the problem is I need to create the dynamic values to drop down box the values which are come from mysql.the following is code which i used in controller:
$wires = $this->wire->find('all',array('conditions'=>array('wire_id'=>$wire_id)));
foreach($wires as $key=>$gs) {
$options[$gs['wires']['type_of_wire']] = $gs['wires']['type_of_wire'];
$options1[$gs['wires']['length']] = $gs['wires']['length'];
$options2[$gs['wires']['color']] = $gs['wires']['color'];
}
In ctp
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdn', 'options'=> $options, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdns', 'options'=> $options1, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
echo $this->Form->input('wire', array('type' => 'select', 'class'=>'dropdned', 'options'=> $options1, 'selected'=> $options, 'div'=>false, 'label'=>false,'id'=>'metal'));
Here I create three drop down boxes, but the problem is if I changed the drop down box value type of wire means its dynamically change its correct length and color for rest of the drop down box.
I also tried it ob onchange but I can't.
Use AJAX calling for dynamic drop down list. something like this in your layout/ where you have jquery defined..
$('#metal').change(function() {
var wire= $(this).val();
$.ajax({
type: "POST",
url: "HERE GIVE URL TO YOUR ACTION WHERE YOU FETCH DATA FROM TABLE",
data: { wire: wire , submit: "submit" },
success: function(result){
$("#metal").html(result);
}
});
});
})
Then in your controller, action for ajax call--
public function get_wires()
{
$this->autoRender=false;
$value=$_POST['wire'];
$wire_length = $this->wire->find('list',array('fields' => array('wire_length'),'conditions' => array('wire'=>$value)));
foreach($wire_length as $q)
{
$data[]="<option>".$q."</option>";
}
print_r($data);
}
Then post this value you get into your form in view.ctp page.
I have a dropdownlist which updates an ajax field. All works fine but the ajax field does not get filled with data on page load. How can I force the ajax field update, on page load?
This is the dropdownlist in view:
echo CHtml::dropDownList('category_selection_code', '', $cat_list_data,
array('style'=>'width:400px',
'ajax' =>
array(
'type'=>'POST',
'url'=>CController::createUrl('articles/GetContentFields'),
'update'=>'#ExtraContentFields',
)
)
);
*UPDATE
I've found the solution which is working for me:
$(document).ready(function(){
$.ajax({
type: 'POST',
data: {category_selection_code: $('#category_selection_code').val()},
url: '<?php echo CController::createUrl('articles/GetContentFields'); ?>',
success: function(data){
$('#ExtraContentFields').html(data)
}
})
})
Controller for ajax processing articles/GetContentFields is waiting category_selection_code parameter in $_POST array. And we should to set it in the data section of ajax part:
data: {category_selection_code: $('#category_selection_code').val()},
Thnx all for the help.
I don't think what you've done above is correct. Firstly, the fourth parameter to CHtml::dropdownList() function is an HTML options array. See the function signature for CHtml::dropdownList()
Put your AJAX call within
$(document).ready(function() {
//Your call goes in here.
});
Fire change event worked for me.
Also, I found useful CHtml::activeId(..) method.
<?php
$cs = Yii::app()->clientScript->registerScript(
'update-brand-car-on-page-load',
'$(document).ready(function() {
$("#'.CHtml::activeId($model, 't_brand_car').'").change();
});'
);
?>
Maybe this will help:
jQuery(function($) {
$('input name["category_selection_code"]').change();
});