Yii2 call action in each GridView row after page load - ajax

I was wondering whether I can call the action automatically through ajax one by one for each row of the GridView after the page is load.
All I can do now is trigger the call manually through button click, already returned the value correctly.
Here is my GridView:
<?php Pjax::begin(['id' => 'payment-list-view-container', 'timeout' => 5000]); ?>
<?= GridView::widget([
'id' => 'payment-table',
'dataProvider' => $dataProvider,
'resizableColumns' => false,
'tableOptions' => ['class' => 'table table-striped'],
'pjax'=>true,
'pjaxSettings' => [
'options' => [
'id' => 'payment-table',
'enablePushState' => false,
],
],
'columns' => [
[
'class' => 'kartik\grid\SerialColumn',
'header' => 'No.',
],
[
'header' => 'Title',
'attribute' => 'name',
],
[
'attribute' => 'date_start',
'header' => 'Payment Date',
'value' => function($model){
return Yii::$app->formatter->asDatetime($model->payment_date, "php:d F Y");
}
],
[
'header' => 'Action',
'format' => 'raw',
'value' => function($model) use ($export_type){
return Html::a('Open', '',
[
'data-url'=>'/model/payment/check-status/id/'. $model->id . '?exportType=' . $export_type ,
'class'=>'check-payment-status'
]);
}
],
],
]); ?>
<?php Pjax::end(); ?>
Here is my js:
<?php
$js = <<<JS
$(document).ready(function(){
function checkStatus() {
$(".check-payment-status").off().on("click", function(e){
e.preventDefault();
var url = $(this).attr("data-url");
$.pjax.defaults.timeout = false;
$.ajax({
url : url,
type : "post",
dataType: 'json',
success: function (response) {
// do something
}, error : function () {
// do nothing
}
});
});
}
checkStatus();
});
JS;
$this->registerJs($js);
I guess I need to use something like this, but still don't know how to implement it
$.each($('.check-payment-status'), function (i, el) {
//do something
});
So can I really do that? Calling the action automatically after the page load for each row?

All you need to do is to trigger the click event on the buttons.
$(document).ready(function() {
//bind the click handler
$('.btn').on('click', function(e) {
e.preventDefault();
console.log("Clicked " + $(this).text());
});
//click each button
$('.btn').each(function() {
$(this).trigger('click');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link 1<br>
Link 2<br>
Link 3<br>

Related

message: "CSRF token mismatch." Error 419

Hello I am trying to post data via ajax but i face this error and i am sure that i called CSRF_TOKEN in header section
Header Section :
meta name="csrf-token" content="{{ csrf_token() }}"
Route Section :
Route::post('cart/data/store/{id}', [CartController::class, 'AddToCart']);
Ajax Code :
function addToCart() {
var product_name = $('#pname').text();
var id = $('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity = $('#qty').val();
$.ajax({
type:"POST",
dataType:"JSON",
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url: "cart/data/store/"+id,
success:function(data) {
$('#closeModal').click();
console.log(data)
}
})
}
Controller :
class CartController extends Controller
{
public function AddToCart(Request $request, $id) {
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->selling_price,
'weight' => 1,
'options' => [
'image' => $product->product_thumbnail,
'size' => $request->size,
'color' => $request->color,
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
} else {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->discount_price,
'weight' => 1,
'options' => [
'size' => $request->size,
'color' => $request->color,
'image' => $product->product_thumbnail
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
}
}
}
Token Section :
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
}
add #csrf in beginning of your form.
<form id="my_form" >
#csrf
<input type="text" name="name"id="name" >
<button type="submit">submit</button>
</form>

Ajax with Laravel Form Collective

{!! Form::select('jobsList[]', $list_of_jobs, null, ['id' => 'job', 'class' => 'form-control' 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!}
I have this form and I am trying to load $list_of_jobs asynchronously compared to what I am doing. I am kind of confused with the way LaravelCollective Form works. Can anyone point out how I would pass that? I already have ajax call that goes and grabs the $list_of_jobs from the controller
//...
{!! Form::select('jobsList[]', [], null, ['id' => 'job', 'class' => 'form-control' 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!}
..//
Populating your select box using JQUERY, AJAX
<script>
$(document).ready(function() {
//Make an Ajax request to a Laravel route
//This will return the data that we can add to our Select element.
$.ajax({
url: 'YOUR URL GOES HERE',
type: 'get',
success: function(data){
//Log the data to the console so that
//you can get a better view of what the script is returning.
console.log(data);
$.each(data, function(key, value){
//Use the Option() constructor to create a new HTMLOptionElement.
var option = new Option(key, value);
//Convert the HTMLOptionElement into a JQuery object that can be used with the append method.
$(option).html(value);
//Append the option to our Select element.
$("#job").append(option);
});
}
});
});
</script>
data must be an array of objects [{}, {}, {}]
[
{'key' : 'foo', 'value' => 'bar'},
{'key' : 'kosksi', 'value' => 'makrouna'},
{'key' : 'lablebi', 'value' => 'kafteji'}
]
Update
If you want to set selected option(s) when Populating your select box :
You need to return an extra attribute selected : true|false in each object of data collection
[
{'key' : 'foo', 'value' : 'bar', 'selected' : false},
{'key' : 'kosksi', 'value' : 'makrouna', 'selected' : false},
{'key' : 'lablebi', 'value' : 'kafteji', 'selected' : true}
]
Then in success() ajax function callback
//...
$.each(data, function(key, elem){
//Use the Option() constructor to create a new HTMLOptionElement.
var option = new Option(elem.value, elem.key, false, elem.selected);
//Convert the HTMLOptionElement into a JQuery object that can be used with the append method.
$(option).html(elem.value);
//Append the option to our Select element.
$("#job").append(option);
});
//...

Laravel validate incoming ajax using request

I have a view like this:
// snippet of view
<td><input class="form-field" type="text" id="entity" name="name" data="{{$entity->id}}" value="{{$entity->name}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>
<td><input class="form-field" type="text" id="entity" name="type" value="{{$entity->type}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>
Which has an ajax:
function updateEntity(value, name, data, id) {
$.ajax({
url: '/entityadmin/' + value + '/' + name + '/' + data + '/' + id,
method: 'POST',
dataType: 'json',
success: function(save) {
$('.messages').append('<div class="alert alert-success">Type Updated!<div>');
setTimeout(function() {
$(".alert").fadeTo(2000, 500).slideUp(500, function(){
$(".alert").slideUp(500);
});
}, 4000);
},
error: function(data) {
console.log(data);
$('.messages').append('<div class="alert alert-danger">Error, please try again!<div>');
setTimeout(function() {
$(".alert").fadeTo(2000, 500).slideUp(500, function(){
$(".alert").slideUp(500);
});
}, 4000);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Controller:
public function entityUpdate($value, $name, $data, $id, EntityRequestUpdate $request) {
$request->$name = $value; //like this?
if($data == "entity") {
$save = Entity::find($id);
}else{
$save = User::find($id);
}
$save->$name = $value;
$save->save();
return response()->json(['results' => $save]);
}
and request:
public function rules()
{
return [
'startdate' => 'required|date',
'endate' => 'nullable|date',
'startime' => 'required|time',
'endtime' => 'required|time',
'title' => 'required',
'type' => 'required',
'description' => 'required',
'frequency' => 'required',
'interval' => 'nullable|numeric',
'monthday' => 'nullable|numeric|min:1|max:3',
'weekday' => 'nullable|alpha|max:3',
'month' => 'nullable|numeric',
'until' => 'nullable|date',
'tags' => 'nullable',
'img' => 'nullable|file|image',
];
}
The thing is it only has to validate one field because one field is being changed each time, how can I use this validation to validate the incoming variable and return errors to ajax with the message on the error if there is any?
You can manually create a validator to validate this one field like so:
$validator = Validator::make(
[ 'name' => $value ],
collect($this->rules())->only([$name])->all()
);
This validator will take the name validator from the defined rules and check that against the first array of values.

Yii2 Select2 multiselect dependent fields

How can I do: I have 2 multi-select fields Select2, the first field for Branches, second for Workers.
When I choose branches, in second field I need to show Workers, who work in this branches.
View file
<label><?= $model->getAttributeLabel('branch') ?></label>
<?php echo Select2::widget([
'name' => 'branch',
'id' => 'branches',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => $branchList,
'options' => [
'placeholder' => Yii::t('app', 'Choose branch'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);?>
<label><?= $model->getAttributeLabel('Workers') ?></label>
<?php echo Select2::widget([
'name' => 'worker',
'id' => 'workers',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => [],
'options' => [
'placeholder' => Yii::t('app', 'Choose workers'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);
?>
JS
$("#branches").change(function(){
change();
});
function change() {
var selectValue = $("#branches").val();
$("#workers").empty();
$.post( "'.Yii::$app->urlManager->createUrl('constructor/lists?id=').'"+selectValue,
function(data){
$("#workers").html(data);
}
);
};
ConstructorController
public function actionLists($id)
{
if ($id != null) {
$ids = explode(",", $id);
foreach ($ids as $id_branch) {
$workers = Report::getWorkers($id_branch);
if (count($workers) > 0) {
foreach ($workers as $worker) {
echo "<option value='" . $worker . "'>" . $worker . "</option>";
}
} else {
echo "'<option>-</option>'";
}
}
}
}

Open modal at the click of a button in a gridview Yii2

I need this button in grid open a modal , but is not working
this is the column:
['class' => 'yii\grid\ActionColumn',
'template' => '{getRespostaPossivel}',
'buttons' => [
'getRespostaPossivel' => function ($url, $model) {
if($model->classeResposta->indr_resposta_possivel){
return Html::buttonInput('Respostas Possíveis',['class'=>'btn btn-primary btn-xs','id' => 'modal-open','onclick' =>
"$('#modal').modal('show');
$.ajax({
url : 'getFormRespostaPossivel',
data : {'id' : $model->id},
success : function(data) {
$('.modal-body').html(data);
}
});
"]);
}
},
],
],
and action:
public function actionGetFormRespostaPossivel($id)
{
$searchModel = new RespostaPossivelUsuarioSearch();
$searchModel->tblcaus_id = $id;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('_form', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
],true,true);
}
someone could help me with this problem ?

Resources