$.fn.yiiGridView.update('sopodetail-grid'+itemcd);
this function it's not running.
It says Cannot call method 'update' of undefined in console.
I have problem when inserting data via ajax gridview not refreshing.
I render multiple grid view with foreach looping, and make each of them unique id with concatenating item_cd.
function validateDetailForm()
{
var jForm = $('#sopodetail-form');
var data = jForm.serialize();
var itemcd = $('#cmbitemcd').val();
$.ajax({
type: 'POST',
url : jForm.attr('action'),
data: data,
dataType:'html',
success:function(data)
{
$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");
$.fn.yiiGridView.update('sopodetail-grid'+itemcd);
},
error: function(data) { // if error occured
alert('Error occured.please try again');
$('#detail-content').html(data);
},
});
}
this how i can render multiple gridview i concating the id...
foreach($modelSoDet as $modelSoDetObj):
$this->widget('zii.widgets.CDetailView', array(
'data'=>$modelSoDetObj,
'attributes'=>array(
'item_cd',
'item.item_name',
'item.item_desc',
'qty',
'qty_purchased'
)
));
$modelSoPoDetail = new Sopodetail();
$modelSoPoDetail->unsetAttributes();
$modelSoPoDetail->so_cd = $modelSoDetObj->so_cd;
$modelSoPoDetail->item_cd = $modelSoDetObj->item_cd;
$gridid = 'sopodetail-grid'.$modelSoPoDetail->item_cd;
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$modelSoPoDetail->search(),
'summaryText' => '',
'id'=>$gridid,
'columns'=>array(
'type',
'po_cd',
'qty'
)
));
endforeach;
You should simply try with the right syntax :
$('sopodetail-grid'+itemcd).yiiGridView('update');
$.param.querystring is called from the yiiGridView.update and is located in the jquery.ba-bbq.js.
check your HTML source if you have the jquery.ba-bbq.js included...
If the jquery.ba-bbq.js is included then you may be recreating the jQuery object after jquery.ba-bbq.js. E.g. jQuery is loaded more than once....
Source: http://www.yiiframework.com/forum/index.php/topic/9387-cgridview-update/
Related
I am trying to save to a database in yii2 using ajax but I am getting errors. I just want to insert the value or rate which is "up" into the database and I don't want to use a form, just on-click of a button.
This is my controller
public function actionThumbs()
{
$thumbs = new Thumbs;
$thumbs->user = Yii::$app->user->identity->email;
$thumbs->topic_id = Yii::$app->getRequest()->getQueryParam('id');
$thumbs->rate = $_POST["rate"];
if ($thumbs->load(Yii::$app->request->post()) ) {
$thumbs->load($_POST);
$thumbs->save();
return $this->redirect(['blog', 'id' => Yii::$app->getRequest()->getQueryParam('id')]);
}
return $this->redirect(['blog','id' => Yii::$app->getRequest()->getQueryParam('id')]);
}
This is my this is my ajax file
$("#mys").click(function() {
var rate = "up";
$.ajax({
type: 'POST',
url: 'vot/frontend/web/index.php?r=site%2Fthumbs',
data: 'rate='+rate,
success: function (rate) {
alert("test");
},
error: function (exception) {
alert(exception);
}
});
});
the view
<div>
<?= Html::Button('ups', ['class' => 'btn btn-primary', 'name' => 'mys' ,'id'=>'mys']) ?>
</div>
I get this alert error
The page at localhost says":
"[object Object]"
By default Yii2 controller doesn't accept POST request without _csrf protection, so there are 2 ways here:
1 - disable csrf:
public function actionThumbs() {
$this->enableCsrfValidation = false;
//your code here
}
2 - Send post request via ajax with _csrf token:
In your layout/main.php file, put this: <?= Html::csrfMetaTags() ?>
Before your "ajax" code, call this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
//Your ajax code here
I am using kartik select2 widget in my yii2 basic app. now i have to display province names in select2 widget on ajax call. It is working fine if i put it directly in form. however not working with ajax call.
Here are my form fields:
<?= $form->field($model, 'role')->dropDownList(
ArrayHelper::map(SubAdminRoles::find()->all(), 'id', 'role_name'),
[
'prompt' => 'Select Role',
'onchange' => '
if($(this).val() != 3) {
$( "#user_area" ).html("showLoading");
$.post( "fetch-area-list?id='.'"+$(this).val(),
function(data) {
$( "#user_area" ).html(data);
})
}'
]
) ?>
<div id="user_area">
</div>
And here is my action code
public function actionFetchAreaList($id) {
// $this->layout = 'none';
$data = [];
if($id == 1) {
$provinceList = \app\modules\adminpanel\models\ProvinceMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($provinceList as $obj) {
$data[$obj['id']] = $obj['province_name'];
}
//print_r($data);
//exit;
} else if($id == 2) {
$subDistrictList = \app\modules\adminpanel\models\SubDistrictMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($subDistrictList as $obj) {
$data[$obj['id']] = $obj['sub_district_name'];
}
}
echo '<label class="control-label">Select Province</label>';
echo Select2::widget([
'name' => 'state_2',
'value' => '1',
'data' => $data,
'options' => ['multiple' => true, 'placeholder' => 'Select Province']
]);
exit;
}
now when i try to get it through ajax i comes with display:none property so i am not able to show my select2 box.
I Also tried changing display:none to display:block in select2 class. In that case i got the select box, but is simple html multiple select box not select2 widget.
How to get it from controller using ajax call?
Thanks in advance.
It is bad practice to render html inside action.
In your case widget requires related JS for initialization. But it will not include in your response.
Move all your html to view area-list and render using following code:
public function actionFetchAreaList($id) {
$this->layout = false;
// ... preparing data
return $this->renderAjax('area-list', [
// ... some view data
]);
}
Method renderAjax renders a named view and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.
I also have similar project like this.
I have 2 combobox (using select2). When select a district from the first combobox. It will call an ajax request to get province list and fill into the second combobox.
Here is my solution:
Using Select2 widget as normally in form
Using javascript to call ajax request and change data of the second combobox.
My controller response data in json format.
$('#district-selector').on('change', function() {
var districtId = $(this).val();
var url = $(this).attr('tb_href');
$('#province-selector').html('');
$.get(
url,
{
city_id: districtId
},
function(response) {
if (response.error == 0 && response.data.length) {
$('#province-selector').append(new Option('', ''));
$.each(response.data, function() {
console.log(this.id + '--' + this.title);
var newOption = new Option(this.title, this.id);
$('#province-selector').append(newOption);
});
}
$('#province-selector').trigger('change');
}
);
});
Demo: demo link
I am sending values from view to controller
Here is my Script :
<script>
$(document).ready(function() {
var vehicle_data = [];
$("#vehicle_submit").click(function(event) {
event.preventDefault();
vehicle_data.push($("#_token").val());
vehicle_data.push($("#VehicleNo").val());
vehicle_data.push($("#VehicleName").val());
$.ajax({
type: "POST",
url: "{{ URL::to('vehicle-process') }}",
data: "vehicle_arr=" + vehicle_data,
async: true,
success: function(data) {
console.log(data);
}
}, "json");
});
});
</script>
I am sending the values VehicleNo and VehicleName to the vehicle-process controller as a single array named as vehicle_arr using POST Method.
Now in the controller :
public function vehicle_process()
{
$a = Input::except(array('_token')) ;
$rule = array(
'VehicleNo' => 'required',
'VehicleSeats' => 'required'
);
$validator = Validator::make($a, $rule);
if ($validator - > fails()) {
$messages = $validator - > messages();
return $messages;
}
else
{
$table = new VehicleModel;
$table->VehicleNo=$VehicleNo; // How can i get the value of VehicleNo and Vehcle Name
$table->save();
}
The Validator can't able to analyze the name of the element i.e., VehicleNo or VehicleSeats,
So whenever i pass the data from view it was showing VeihcleNo required validator messages all the time.
Can i make the validator like
$rule = array(
$a['VehicleNo'] => 'required',
$a['VehicleSeats'] => 'required'
);
as i am storing the all the values in $a.
I even tested return $a; to view all elements in the controller it shows like
Object {vehicle_arr: "wBNTzuTY20GL6BR147TIM9l8mxpCbgMAM7ok7fD4,EZ-55,35"}
Is it possible to get values like
$value = Input::post('VehicleNo');
So, How can i get the values extract so that i can done with the validation and store in db
My Model just has the Table Name
So i just need the way to get the value of $VehicleNo to store in db. So that i can construct this
$table->VehicleNo=$VehicleNo;
$table->save();
Update : It is ok even if i change the method to POST to GET in order to achieve my Result
im receiving this error. It looks like it's not seeing the id of my clistview, it doesn't even show up on inspect, which is weird.
But I am giving it an id..
<?php $this->widget('zii.widgets.CListView', array(
'id'=>'how',
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>'{items} {pager}',
'pager' => array(
'class' => 'ext.infiniteScroll.IasPager',
'rowSelector'=>'.left-pwrapper',
'listViewId' => 'how',
'header' => '',
'loaderText'=>'Loading...',
'options'=>array('onRenderComplete'=>'js:function () {
$.each($(".left-pwrapper"), function(){
if(typeof $.fn.yiiListView.settings["\'"+$(this).attr("id")+"\'"]=="undefined")
$(this).yiiListView();
});
}')),
)); ?>
When i go to element inspect, the error shows up here:
$.fn.yiiListView.update = function(id, options) {
var customError,
settings = $.fn.yiiListView.settings[id];
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
options = $.extend({
type: settings.ajaxType,
url: $.fn.yiiListView.getUrl(id),
[[[Cannot read property 'ajaxType' of undefined ]]]
I have seen the answers on this, this, and this question, but none of them solved my issue.
What fixed it for me was setting the ajaxUpdate option of yiiListView in the js call from where I called update, as follows:
$(element).yiiListView({
'ajaxUpdate': [
'1', element
]
});
$.fn.yiiListView.update(element, {
//...
});
I tried below codes and it worked for me. You can give it a try 😊
Assign $listView variable to $this->widget
<?php $listView = $this->widget('zii.widgets.CListView', array(...)); ?>
Add codes at the end of the view which contains your list view
<?php
$id = $listView->htmlOptions['id'];
$options = $listView->registerClientScript();
?>
<script type='text/javascript'>
/*<![CDATA[*/
jQuery(function($) {
jQuery('#<?php echo $id; ?>').yiiListView(<?php echo $options; ?>);
});
/*]]>*/
</script>
When using the function
$.fn.yiiListView.update('id');
DO NOT USE a #
Incorrect:
$.fn.yiiListView.update('#myList');
Correct:
$.fn.yiiListView.update('myList');
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.