Dynatable.js remove an element from a stylized list and update count - html-lists

I am using for the most part the default code from the dynatable website for a stylized list.
I really like it as i get search on all my fields. here is the html code and the javascript code:
<ul id="ul-example" class="row-fluid no-bullets">
<?php foreach ($dms as $k => $v): ?>
<li class="span12" data-color="gray" id="manage_vehicle_id_<?= $v['id'];?>">
<div class="thumbnail">
<div class="thumbnail-image">
<center>
<img src="<?= $v['image']; ?>" width="220" height="180" />
</center>
</div>
<div class="caption">
<center>
<h5><?= $v['year'] . ' ' . $v['make'] . ' ' . $v['model'] . ' ' . $v['trim'];?></h5>
</center>
<hr>
<center>
<p><b>Vin:</b> <?= $v['vin']; ?></p>
<p><b>Stock #:</b> <?= $v['stock'];?></p>
</center>
<hr>
<p>
<center>
<button class="btn btn-primary" onclick="getVehicleDetailsByid('<?= $v['id']; ?>');"><i class="fa fa-edit"></i> Edit</button>
<button class="btn btn-danger" onclick="openDeleteVehicleByIdModal('<?= $v['id']; ?>', '<?= $v['vin']; ?>', '<?= $v['stock'];?>');"><i class="fa fa-minus"></i> Delete</button>
</center>
</p>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
function ulWriter(rowIndex, record, columns, cellWriter) {
var cssClass = "span12", li;
if (rowIndex % 3 === 0) { cssClass += ' first'; }
li = '<li class="' + cssClass + '" id="'+record.id+'" data-row-index="'+rowIndex+'"><div class="thumbnail"><div class="thumbnail-image">' + record.thumbnail + '</div><div class="caption">' + record.caption + '</div></div></li>';
return li;
}
// Function that creates our records from the DOM when the page is loaded
function ulReader(index, li, record) {
var $li = $(li),
$caption = $li.find('.caption');
record.thumbnail = $li.find('.thumbnail-image').html();
record.caption = $caption.html();
record.label = $caption.find('h5').text();
record.description = $caption.find('p').text();
record.color = $li.data('color');
record.id = $li.attr('id');
record.index = $li.attr('data-row-index');
}
$( '#ul-example' ).dynatable({
table: {
bodyRowSelector: 'li'
},
writers: {
_rowWriter: ulWriter
},
readers: {
_rowReader: ulReader
},
features: {
paginate: false,
sort: true,
search: true,
recordCount: true,
perPageSelect: false
},
inputs: {
searchTarget: '#manage_vehicle_search',
recordCountTarget: '#manage_vehicle_recordCount'
}
});
as you can see in the html i have a delete button that removes the record. I can remove it manually. However it is not actually removed. When a search query happens the item is still in the list.
I remove it with:
$( '#manage_vehicle_id_'+id ).remove();
var dynatable = $('#ul-example').data('dynatable');
dynatable.domColumns.removeFromArray(index);
dynatable.dom.update();
I am getting an error here something like column.length is null. I can see the this.remove method in dynatable is throwing an error.
How can i remove this item from the list and update dynatable dom and the get the right count?
Thanks

I solved this issue by using dynatable.process() instead of remove/update. Not sure if it's the proper solution, but it worked for me.
$( '#manage_vehicle_id_'+id ).remove();
var dynatable = $('#ul-example').data('dynatable');
dynatable.process();

Related

Conditional Component variable value increment Vue/Laravel

[1]so i have a laravel project going on, and i want to increment the value of the variable deliver_later_num, depending on the "deliver_today" present in the same component in the items[] array, which i am outputting in the template file, i cannot figure how to do it, i do not know if i can increment the value on the template side or on the component side. here is the component code:
cartContent = new Vue({
el: '#cartList',
data: {
items: [], //array containing all the items
deliver_later_num: 0, //value to increment
},
methods: {
remove: function (product_id) {
removeProductIfFromCart(product_id);
},
incQuantity: function (product_id){
incCart(product_id)
},
decQuantity: function (product_id){
decCart(product_id)
},
}
})
here is the template file :
<div id="cartList">
<div v-for="item in items" class="items col-xs-12 col-sm-12 col-md-12 col-lg-12 clearfix">
<div class="info-block block-info clearfix" v-cloak>
<div class="square-box pull-left">
<img :src="item.attributes.image" class="productImage" width="100" height="105" alt="">
</div>
<h6 class="product-item_title">#{{ item.name }}</h6>
<p class="product-item_quantity">#{{ item.quantity }} x #{{ item.attributes.friendly_price }}</p>
<ul class="pagination">
<li class="page-item">
<button v-on:click="decQuantity(item.id)" :value="item.id" class="page-link" tabindex="-1">
<i class="fa fa-minus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="incQuantity(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-plus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="remove(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-trash"></i>
</button>
</li>
<input hidden class="delivers_today_state" type="text" :value=" item.attributes.delivers_today "> // if this equals 0 i want to increment the deliver_later_num value
</ul>
</div>
</div>
</div>
laravel controller code :
public function add(Request $request){
$item = Items::find($request->id);
$restID=$item->category->restorant->id;
//Check if added item is from the same restorant as previus items in cart
$canAdd = false;
if(Cart::getContent()->isEmpty()){
$canAdd = true;
}else{
$canAdd = true;
foreach (Cart::getContent() as $key => $cartItem) {
if($cartItem->attributes->restorant_id."" != $restID.""){
$canAdd = false;
break;
}
}
}
//TODO - check if cart contains, if so, check if restorant is same as pervious one
// Cart::clear();
if($item && $canAdd){
//are there any extras
$cartItemPrice=$item->price;
$cartItemName=$item->name;
$theElement="";
//Is there a varaint
//variantID
if($request->variantID){
//Get the variant
$variant=Variants::findOrFail($request->variantID);
$cartItemPrice=$variant->price;
$cartItemName=$item->name." ".$variant->optionsList;
//$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
foreach ($request->extras as $key => $value) {
$cartItemName.="\n+ ".$item->extras()->findOrFail($value)->name;
$cartItemPrice+=$item->extras()->findOrFail($value)->price;
$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
Cart::add((new \DateTime())->getTimestamp(), $cartItemName, $cartItemPrice, $request->quantity, array('id'=>$item->id,'variant'=>$request->variantID, 'extras'=>$request->extras,'restorant_id'=>$restID,'image'=>$item->icon,'friendly_price'=> Money($cartItemPrice, env('CASHIER_CURRENCY','usd'),true)->format(),'delivers_today' => $item->deliverstoday ));
return response()->json([
'status' => true,
'errMsg' => $theElement
]);
}else{
return response()->json([
'status' => false,
'errMsg' => __("You can't add items from other restaurant!")
]);
//], 401);
}
}
public function getContent(){
//Cart::clear();
return response()->json([
'data' => Cart::getContent(),
'total' => Cart::getSubTotal(),
'status' => true,
'errMsg' => ''
]);
}
link to the items array vue dev tools screenshot
[1]: https://i.stack.imgur.com/smLRV.png
thanks for your precious help and time.
A computed property can be used if the deliver_later_num is only dependent on the presence/absence of deliver_today on elements of items array
cartContent = new Vue({
el: '#cartList',
data: {
items: {}
},
computed: {
deliver_later_num() {
let num = 0;
Object.keys(this.items).forEach(key => {
let item = this.items[key];
Object.keys(item).forEach(k => {
if(k === 'deliver_today' && item[k]) {
num++;
}
});
});
return num;
},
}

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

How to use variable data after Ajax Call Success - Laravel

I created a small file manager to manage my files. On the one hand, the folder structure is shown thanks to JsTree. On the right I would like that based on the click on the left folder I was shown the files contained in that folder.
At the click an Ajax call is made which calls the selectFiles method to go through the routes. Now in the console i see the correct data, but i don't know how to use it into foreach in the blade.
AJAX:
// chiamata Ajax per selezionare files in base all'id
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
console.log('Succes!',data);
},
error : function(err) {
console.log('Error!', err);
},
});
});
DocumentiController.php:
/**
* Selzionare files in base all'id della cartella
*/
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json(compact('files'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
Route:
Route::post('archivio_documenti/{id}/selectFiles', 'DocumentiController#selectFiles');
Update:
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
OK, the foreach of yours is a bit complex, but the idea itself is simple: recreate the foreach loop from your Blade in Javascript and append the result to the DOM.
In your success callback you could e.g. do this:
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
// Build the HTML based on the files data
var html = '';
$.each(data, function(i, file) {
html += '<div class="file" id="file_' + file.id + '">' + file.updated_at + '</div>';
});
// Append the built HTML to a DOM element of your choice
$('#myFilesContainer').empty().append(html);
},
error : function(err) {
console.log('Error!', err);
},
});
});
Obviously, this is simplified and you'd need to use the HTML structure you've shown us in the foreach loop above, but the idea is the same: (1) loop through your files in the data object and build the HTML structure row by row, (2) put the whole HTML block in the DOM, wherever you need it to be displayed after the user clicked on a folder.
Alternative:
If you'd like to keep the foreach loop in Blade instead of of Javascipt, you could move the loop to a separate blade:
folder_contents.blade.php
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
Then, in your controller:
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
// Save the view as string
$view = view('folder_contents.blade.php', compact('files')))->render();
// Pass the ready HTML back to Javasctipt
return response()->json(compact('view'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
you must set header for ajax
headers: {
'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
and in Controller
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json($files);
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}

How to sort only the displayed items in table with vue

I have two questions regarding the following code.
1st problem: say I have four items in the array with ids of [1,2,4,5,7]
If I click on the sort and i have 2 items per page chosen then it will show me entries with id's of 1&2 or 5&7 as I toggle the reverse order.
So how can I get the table to just sort the items that are displayed in the paginated view?
2nd problem:
We are using a mixture of vue and some jquery from an admin template we purchased, But where it has <div class="checkbox checkbox-styled"> written in the code the check boxes will not render unless I put the Vue code in a setTimeout with an interval val of '100' or more.
And it generally just doesn't render stuff in jquery well if the item that relies on jquery is in a vue for loop.
Has anyone got an explanation for this?
Please note I've deleted as much out of this to keep the question as small as possible.
<div class="section-body">
<!-- BEGIN DATA TABLE START -->
<form class="form" role="form">
<div class="row">
<div class="col-lg-12">
<div id="" class="dataTables_wrapper no-footer">
<div class="table-responsive">
<table style="width: 100%" cellpadding="3">
<tr>
<td>
<div class="dataTables_length" id="entries_per_page">
<label>
<select name="entries_per_page" aria-controls="datatable" v-model="itemsPerPage">
<option value='2'>2</option>
<option value='20'>20</option>
<option value='30'>30</option>
</select>
entries per page
</label>
</div>
</td>
</tr>
</table>
<table class="table table-striped table-hover dataTable">
<thead>
<tr>
<th>
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" v-model="selectAll" :checked="allSelected" #click="selectAllCheckboxes">
</label>
</div>
</th>
<th v-bind:class="{'sorting': col.key !== sortKey, 'sorting_desc': col.key == sortKey && !isReversed, 'sorting_asc': col.key == sortKey && isReversed}" v-for="col in columns" #click.prevent="sort(col.key)">
<a href="#" v-cloak>${ col.label | capitalize}</a>
</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items | paginate | filterBy search">
<td width="57">
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" value="${ item.id }" v-model="cbIds" :checked="cbIds.indexOf(item.id) >= 0" />
</label>
</div>
</td>
<!-- !ENTITY_NAME TABLE COLUMNS START -->
<td v-cloak>${ item.id }</td>
<td v-cloak>${ item.title }</td>
<!-- !ENTITY_NAME TABLE COLUMNS END -->
<td class="text-right">
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Edit row" #click="editItem(item)">
<i class="fa fa-pencil"></i></button>
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Delete row" #click="deleteModalOpened(item)">
<i class="fa fa-trash-o"></i>
</button>
</td>
</tr>
</tbody>
</table>
<!-- PAGINATION START -->
<div class="dataTables_info" role="status" aria-live="polite" v-if="resultCount > 0" v-cloak>
Showing ${ currentCountFrom } to ${ currentCountTo } of ${ resultCount } entries
</div>
<div class="dataTables_paginate paging_simple_numbers" id="datatable_paginate" v-if="resultCount > 0">
<a class="paginate_button previous disabled" #click="previousPage()" v-if="currentPage==0">
<i class="fa fa-angle-left"></i>
</a>
<a class="paginate_button previous" #click="previousPage()" v-else>
<i class="fa fa-angle-left"></i>
</a>
<span v-for="pageNumber in totalPages">
<a class="paginate_button current" #click="setPage(pageNumber)" v-show="pageNumber == currentPage" v-cloak>${ pageNumber + 1 }</a>
<a class="paginate_button" #click="setPage(pageNumber)" v-show="pageNumber != currentPage" v-cloak>${ pageNumber + 1 }</a>
</span>
<a class="paginate_button next disabled" #click="nextPage()" v-if="currentPage == (totalPages - 1)">
<i class="fa fa-angle-right"></i>
</a>
<a class="paginate_button previous" #click="nextPage()" v-else>
<i class="fa fa-angle-right"></i>
</a>
</div>
<!-- PAGINATION END -->
</div>
</div>
</div>
</div>
</form>
<!-- BEGIN DATA TABLE END -->
</div>
<script>
Vue.config.delimiters = ['${', '}'];
new Vue({
el: '#app',
data: {
items: [],
columns: [
{
key: 'id' ,
label: 'id' ,
},
{
key: 'title' ,
label: 'title' ,
},
],
// ALL PAGINATION VARS
currentPage: 0,
itemsPerPage: 20,
resultCount: 0,
totalPages: 0,
currentCountFrom: 0,
currentCountTo: 0,
allSelected: false,
cbIds: [],
sortKey: '',
isReversed: false
},
computed: {
totalPages: function() {
return Math.ceil(this.resultCount / this.itemsPerPage);
},
currentCountFrom: function () {
return this.itemsPerPage * this.currentPage + 1;
},
currentCountTo: function () {
var to = (this.itemsPerPage * this.currentPage) + this.itemsPerPage;
return to > this.resultCount ? this.resultCount : to;
}
},
ready: function() {
this.pageUrl = '{{ path('items_ajax_list') }}';
this.getVueItems();
},
filters: {
paginate: function(list) {
this.resultCount = this.items.length;
if (this.currentPage >= this.totalPages) {
this.currentPage = Math.max(0, this.totalPages - 1);
}
var index = this.currentPage * this.itemsPerPage;
return this.items.slice(index, index + this.itemsPerPage);
}
},
methods : {
sort: function (column) {
if (column !== this.sortKey) {
this.sortKey = column;
this.items.sort(this.sortAlphaNum);
this.isReversed = false;
return;
}
this.reverse();
if (this.isReversed) {
this.isReversed = false;
}
else {
this.isReversed = true;
}
},
reverse: function () {this.items.reverse()},
sortAlphaNum: function (a, b) {
if (a[this.sortKey] === undefined) return;
if (b[this.sortKey] === undefined) return;
var cva = a[this.sortKey].toString().toLowerCase();
var cvb = b[this.sortKey].toString().toLowerCase();
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var aA = cva.replace(reA, "");
var bA = cvb.replace(reA, "");
if(aA === bA) {
var aN = parseInt(cva.replace(reN, ""), 10);
var bN = parseInt(cvb.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
},
setPage: function(pageNumber) {this.currentPage = pageNumber},
nextPage: function () {
if (this.pageNumber + 1 >= this.currentPage) return;
this.setPage(this.currentPage + 1);
},
previousPage: function () {
if (this.currentPage == 0) return;
this.setPage(this.currentPage - 1);
},
getVueItems: function(page){
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
this.$set('items', res);
});
},
}
});
</script>
Regarding your first problem, You can break the bigger array in smaller arrays, than show those on paginated way and sort the smaller array, I have created a fiddle to demo it here.
Following is code to break it in smaller arrays:
computed: {
chunks () {
var size = 2, smallarray = [];
for (var i= 0; i<this.data.length; i+=size) {
smallarray.push(this.data.slice(i,i+size))
}
return smallarray
}
}
Regarding your second problem, if the issue is that items is not getting properly populated after this.$http.get call, it can be due to wrong scope of this variable as well, which can be corrected like following:
getVueItems: function(page){
var self = this
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
self.items = res;
});
},

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources