Ajax with Laravel Form Collective - laravel

{!! 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);
});
//...

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>

Yii2 call action in each GridView row after page load

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>

Symfony filter form for multi select dropdown values

I have a filter form which I would like to apply on a multiselect dropdown. So there's a "apply" button for the filters and when clicking it, I'd like to update the values in the dropdown according to the filter choices. (There are other fields/values on my form which should not disappear when updating the dropdown values.)
I have absolutely no clue how to achieve this. Maybe an AJAX function would lead to the solution but I don't know how such one would look like. I would be happy about any tips! :)
What I have so far:
Filter dropdowns for
markets
types and
airlines
They are all multiselect dropdowns. And after selecting them I'd like to hit "apply" and then the 'documentlist'-dropdown should update so that only documents connected to the selected markets/types or airlines are shown.
P.S. What I like to implement in addition, is a search box for document names and IDs. To that I'm not even close an I don't even have the correct elements..
<div class="panel panel-default">
<div class="panel-body">
{{ form_start(filterForm) }}
{{ form_row(filterForm.type) }}
{{ form_row(filterForm.markets)}}
{{ form_row(filterForm.airlines)}}
<input type="submit" class="btn-primary btn btn-xs" value="Apply Filter" />
{{ form_end(filterForm) }}
<br clear="all" />
{{ form_row(form.documentlist) }}
</div>
</div>
update
my form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['data']['url'])
->setMethod('GET')
->add('type', 'choice', array('choices' => array(
'document_types.contract' => 1,
'document_types.general'=>2,
'document_types.goodwill_policy'=>3,
'document_types.pricesheet'=>4,
'document_types.yq_update'=>5,
'document_types.contract_addendum'=>6),
'choices_as_values' => true, 'label' => 'label.types',
'expanded' => false, 'multiple' => true,
'label' => 'label.type',
'translation_domain' => 'Documents'))
;
$user = $this->tokenStorage->getToken()->getUser();
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($user){
$form = $event->getForm();
// only show specific filters based on user's context
$form->add('airlines', 'entity', array(
'class' => 'AppBundle:Airline', 'property' => 'id',
'query_builder' => function (EntityRepository $er) use ($user) {
$airlines = $user->getAirlines();
return $er->createQueryBuilder('a')
->addOrderBy('a.id', 'ASC')
->andWhere('a.id IN (?1)')
->setParameter(1,$airlines);
},
'choice_value' => 'id',
'choice_label' => 'id', 'label' => 'label.airlines',
'expanded' => false, 'multiple' => true,
'translation_domain' => 'Documents'));
$form->add('markets', 'entity', array(
'class' => 'AppBundle:Market', 'property' => 'id',
'query_builder' => function (EntityRepository $er) use ($user) {
$markets = $user->getMarkets();
return $er->createQueryBuilder('m')
->addOrderBy('m.id', 'ASC');
->andWhere('m.id IN (?1)')
->setParameter(1,$markets);
},
'choice_value' => 'id',
'choice_label' => 'id', 'label' => 'label.markets',
'expanded' => false, 'multiple' => true,
'translation_domain' => 'Documents'))
and that's the dropdown, that's supposed to update its content after the previous dropdowns are selected.
->add('documentlist', EntityType::class, array(
'class' => 'DocumentBundle:Document',
'property' => 'name',
'expanded' => false, 'multiple' => true,
'label' => 'label.document_list',
'empty_value' => "Select document",
'required' => false,
'mapped' => false,
'translation_domain' => 'Documents'} ));
}
Well, I'm guessing you're doing an application for Airlines based on your previous posts. Below is some examples that should help you:
// Your PHP Form file
...
->add('local_markets_bool', CheckboxType::class, array( // Show Local Markets?
'label' => 'Local markets:',
'required' => false,
'attr' => array(
'onchange' => "filter('local_markets')"
),
))
...
{# Your Twig file #}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('script/filters.js') }}"></script>
{% endblock %}
// Your Javascript file. Example web/script/filters.js
function filter(type){
var markList = document.getElementById("form_market_list");
var optSub = "<option value='' selected='selected'>Choose an option</option>";
if (type == 'local_markets'){ // Local.
optSub += "<option value='us'>USA</option>";
optSub += "<option value='ca'>Canada</option>";
}
else if (degType == 'americas'){ // TC Degree.
optSub += "<option value='us'>USA</option>";
optSub += "<option value='ca'>Canada</option>";
optSub += "<option value='pa'>Panama</option>";
optSub += "<option value='br'>Brazil</option>";
optSub += "<option value='pe'>Peru</option>";
}
...
markList.innerHTML = optSub;
}
Then when you click the local_markets_bool checkbox, that triggers and onchange() event, and passes in the parameter local_markets and then the code adds the Countries USA and Canada to the list.
You might not want to do it that way, but it gives you and idea. Using jQuery is easier, but the example is just plain Javascript.

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.

cakephp pass select value ajax

I have two select buttons and want to filter records, when user select any option I have to fire a event and pass the values of buttons to the controller's action. my code is as under
view
<?php echo $this->Form->create('Employee'); ?>
<fieldset>
<div class="pure-control-group">
<?php echo $this->Form->input('designation', array("label" => "Designation",'type' => 'select', 'id'=>'DesignationType','options' => $settings,'empty' => 'select'));?>
<?php echo $this->Form->input('district', array("label" => "District",'type' => 'select', 'id'=>'districtType','options' => $district,'empty' => 'select'));?>
</div>
</fieldset>
<?php echo $this->Form->end();
$this->Js->get('#DesignationType')->event('change',
$this->Js->request(array(
'controller'=>'employees',
'action'=>'getByCategory'
), array(
'update'=>'#success',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
<div id="success"></div>
controller
public function getByCategory(){
$design_id =$this->request->data['Employee']['designation'];
$district_id =$this->request->data['Employee']['district'];
$this->layout = 'ajax';
}
when i click designation then i m able to get the value of designation but not able to get the value of district .And following error occur
Undefined index: district [APP\Controller\EmployeesController.php, line 18]
so, how can i get the value of district;
Try to send the form id in data variable. that is
Try this :
$data = $this->Js->get('#YourFormId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#DesignationType')->event('change',
$this->Js->request(array(
'controller'=>'employees',
'action'=>'getByCategory'
), array(
'update'=>'#success',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $data
))
);

Resources