Sort and Save table data using jquery sortable - ajax

Hi I am trying to set up a table with parent and child data which can be sorted by using the jquery sortable library, I am able to get the position and the respective ids of the data but unable to send the to the controller using jquery
HTML Part:
<tbody class="sort">
#foreach($menus as $menu)
<tr id = "{{ $menu->id }}" class="parent">
<td>{{$menu->name}}</td>
<td>{{ $menu->link }}</td>
#if($menu->sub == 1)
<td>Active</td>
#else
<td>In-Active</td>
#endif
<td class="text-right" >
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="{{$menu->id}}" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
#if(count(App\Menu::where('parent_id',$menu->id)->orderBy('position','asc')->get())>0)
#foreach(App\Menu::where('parent_id',$menu->id)->orderBy('position','asc')->get() as $child)
<tr id="{{ $child->id }}">
<td>~{{$child->name}}</td>
<td>{{ $child->link }}</td>
<td></td>
<td class="text-right" >
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="{{$child->id}}" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
#endforeach
#endif
</tr>
#endforeach
</tbody>
Jquery part:
$(document).ready(function(){
$('.sort').sortable({
stop:function(event, ui){
var parameter = new Array();
var position = new Array();
$('.sort>tr').each(function(){
parameter.push($(this).attr("id"));
});
$(this).children().each(function(index) {
position.push(index + 1);
});
$.ajax({
url:"{{ route('menu.savePosition') }}",
method:"POST",
data:{"id":parameter,"position":position},
success:function(response){
console.log(response);
},
error:function(xhr,response){
console.log(xhr.status);
}
});
},
}).disableSelection();
});
Controller Part:
public function SavePosition(Request $req){
$position = ($req->all());
return $req->all();
// foreach($file as $pos){
// $id = $pos[1];
// $position = $pos[0];
// $menu = Menu::findOrFail($id);
// $menu->position = $position;
// $menu->save();
// }
}
After all this the console looks like the following :
please help me out fixing the issue
any help would be highly appreciated
Thanks in advance

Consider the following example.
$(function() {
$(".sort").sortable({
items: "> tbody > tr",
stop: function(event, ui) {
var parameter = $(this).sortable("toArray");
var position = [];
$.each(parameter, function(index, value) {
position.push(index + 1);
});
console.log(parameter, position);
$.ajax({
url: "{{ route('menu.savePosition') }}",
method: "POST",
data: {
"id": parameter,
"position": position
},
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(status, error);
}
});
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" integrity="undefined" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container">
<table class="sort" width="340">
<thead>
<tr>
<th>Name</th>
<th>Link</th>
<th>Status</th>
<td></td>
</tr>
</thead>
<tbody>
<tr id="item-1">
<td>Item 1</td>
<td>Link 1</td>
<td>Active</td>
<td class="text-right">
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="item-1" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<tr id="item-2">
<td>Item 2</td>
<td>Link 2</td>
<td>Active</td>
<td class="text-right">
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="item-2" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<tr id="item-3">
<td>Item 3</td>
<td>Link 3</td>
<td>Active</td>
<td class="text-right">
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="item-3" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<tr id="item-4">
<td>Item 4</td>
<td>Link 4</td>
<td>Active</td>
<td class="text-right">
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="item-4" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<tr id="item-5">
<td>Item 5</td>
<td>Link 5</td>
<td>Active</td>
<td class="text-right">
<i class="fe-edit-2" ></i>
<button data-toggle="tooltip" data-placement="top" data-id="item-5" title="" data-original-title="Delete" class="delete btn btn-danger ml-1 " type="submit"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
It's not clear why you are sending the position as the Array of items will already be in the order of the items. I did include it just in case you do need it for something else.
It's easier to use the toArray method: https://api.jqueryui.com/sortable/#method-toArray You will also want to properly define the items so that Sortable knows what the items should be.

Try this way.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});

Related

How to hide a button inside a foreach with AlpineJS and Laravel

I am starting to use AlpineJS and I have a table that I fill with fetch.
The question is that I have tried to place x-if and x-show conditionals but they either hide all the buttons or show me all of them.
How could I do it?
<div class="iq-card-body" x-data="serviceTenants()" x-init="loadingTable()">
<table class="table table-bordered table-responsive-md table-striped_ text-center" id="laravel_crud">
<thead>
<tr>
<th>Company</th>
<th>Plan</th>
<th>created at</th>
<td colspan="3"></td>
</tr>
</thead>
<tbody>
<template x-for="tenant in tenants">
<tr>
<td x-text="tenant.name"></td>
<td x-text="tenant.plan"></td>
<td x-text="tenant.created"></td>
<td width="180">
<button class="btn iq-bg-info btn-rounded btn-sm my-0 float-left">Upgrade</button>
<button class="btn iq-bg-danger btn-rounded btn-sm my-0 float-left ml-2" #click="deleteTenant(tenant.id)">{{__('Delete')}}</button>
</td>
</tr>
</template>
</tbody>
</table>
</div>
function serviceTenants(){
return {
tenants: [],
loadBtn: false,
loadingTable(){
fetch('list')
.then(response => response.json())
.then(data => {
this.tenants = data.data;
});
}
}
}
You can use if condition inside the loop.
<template x-for="tenant in tenants">
<div>
<template x-if="tenant.showField === true">
<div>
<button class="btn iq-bg-info btn-rounded btn-sm my-0 float-left">Upgrade</button>
<button class="btn iq-bg-danger btn-rounded btn-sm my-0 float-left ml-2" #click="deleteTenant(tenant.id)">{{__('Delete')}}</button>
</div>
</template>
<template x-if="tenant.showField !== true">
<div>
<button class="btn iq-bg-info btn-rounded btn-sm my-0 float-left">Upgrade</button>
<button class="btn iq-bg-danger btn-rounded btn-sm my-0 float-left ml-2" #click="deleteTenant(tenant.id)">{{__('Delete')}}</button>
</div>
</template>
</div>
</template>

in laravel pass updated value from view to controller without submit button

I am tiring to store manager auth id, I have view page that contents of user tickets, in my database name called "ticket" in that table I have column name called "ticket_view_by_manager_id" in this column I am trying to store manager auth id, when manager open that ticket that time manager auth id, store in this "ticket_view_by_manager_id" column,
my controller
public function manager_assigned_Chat(Request $request, $ticket_id){
$this->validate($request, [
'ticket_view_by_manager_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input['ticket_view_by_manager_id'] = $request->submit;
$input->save();
}
my route
Route::post('user_ticket_chat{ticket_id}', 'Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat{ticket_id}');
my view "showing all user ticket list"
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<form method="POST" action="{{ route('user_ticket_chat{ticket_id}')}}" enctype="multipart/form-data">
#csrf
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<td style="text-align:center"> {{ $key + 1 }} </td>
<td >{{ $my_tickets_list->ticket_id }}</td>
<td > <input type="hidden" name="submit" value="{{ Auth::user()->staff_id }}" href="ticket_chat{{ $my_tickets_list->ticket_id }}" >{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td >{{$my_tickets_list->created_at->todatestring()}} </td>
<td >{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
<input type="submit" value="Send.">
</form>
</tbody>
</table>
in your web.php
Route::post('user_ticket_chat','Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat');
in your controller
public function manager_assigned_Chat(Request $request){
$this->validate($request,[
'ticket_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input->ticket_view_by_manager_id = Auth::user()->id; // or Auth::user()->staff_id; in your case
$input->save();
}
in blade view add meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
in table :
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<tdstyle="text-align:center"> {{ $key + 1 }} </td>
<td>{{ $my_tickets_list->ticket_id }}</td>
<td class="ticket" data-ticketid="{{ $my_tickets_list->ticket_id}}">{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td>{{$my_tickets_list->created_at->todatestring()}} </td>
<td>{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
</tbody>
</table>
now using Jquery AJAX request :
<script>
$(document).on('click','.ticket',function(){
var ticketID=$(this).attr('data-ticket');
$.ajax({
url:'/user_ticket_chat',
type:'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType:'json',
data:{"ticket_id":ticketID},
success:function(response){
console.log(response);
},
error:function(){
alert('Error');
}
});
});
</script>
You should change your validator. It will be like, Please try this:
$this->validate($request, [
'submit' => 'required',
]);
Because your are not sending any info about ticket_view_by_manager_id from view.
Suggestion: may be your code is not well decorated. If you can please
have a look.

How to auto-populate form fields using vue and laravel

I'm developing a web application where I want to populate some field if I type computer_number I want to populate staff_old_name field that will select from staffs table.
This is what I've tried:
Template
<div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Computer Number</th>
<th>Old Name</th>
<th>New Name</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(staff, index) in staffs">
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.computer_number"/></span>
<span v-else>{{staff.computer_number}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.old_name"/></span>
<span v-else>{{staff.old_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.new_name"/></span>
<span v-else>{{staff.new_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.remarks"/></span>
<span v-else>{{staff.remarks}}</span>
</td>
<td>
<span v-if="!staff.editmode"><button class="btn btn-info" type="button" #click="edit(staff)">Edit</button></span>
<span v-else><button class="btn btn-success" type="button" #click="save(staff)">Save</button></span>
<span><button type="button" class="btn btn-danger" #click="remove(index)"><i class="fa fa-trash"></i></button></span>
</td>
</tr>
</tbody>
</table>
<div class="box-footer">
<button class="btn btn-info" type="button" #click="cloneLast">Add Row</button>
</div>
</div>
Script
export default {
data() {
return {
staffs: [],
data_results: []
}
},
computed:{
autoComplete(){
this.data_results = [];
if(this.computer_number.length > 2){
axios.get('/api/staffs/autocomplete',{params: {computer_number: this.computer_number}}).then(response => {
console.log(response);
this.data_results = response.data;
});
}
}
},
methods: {
edit :function(obj){
this.$set(obj, 'editmode', true);
},
save : function(obj){
this.$set(obj, 'editmode', false);
},
remove: function(obj){
this.staffs.splice(obj,1);
},
cloneLast:function(obj){
//var lastObj = this.staffs[this.staffs.length-1];
//lastObj = JSON.parse(JSON.stringify(lastObj));
obj.editmode = true;
this.staffs.push(obj);
},
},
created() {
axios.get('/staff-names')
.then(response => this.staffs = response.data);
},
}
when I type the computer number I want the staff_old_name field populated base on staff name which is stored in staffs table.

ajax reply working but when it load second times

I am updating my cart quantity using ajax. After successfully updating of the cart, when I load the cart and body of the current page the toggle menu of the my cart button does not work the first time. But when I update second time after loading the cart and body the toggle menu works.
My current code:
'remove': function(product_id, flag) {
// alert(product_id);
// alert(flag);
$.ajax({
url: 'includes/addToCart.php',
type: 'post',
data: 'product_id=' + product_id + '&flag='+flag,
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<span class="lg">My Cart</span><span><i class="fa fa-shopping-basket"></i> ('+json['total']+') items</span>');
}, 100);
setTimeout(function () {
// if(json['key'] == "blank")
$('#cart > ul').load('includes/loadcart.php');
}, 100);
setTimeout(function () {
$('body').load('cart.php');
}, 100);
},
});
In the console I am getting this error when it executes:
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user’s experience.
I have used the async: true, and async: false
same problem persists
here is my html code where the value displayed
<div class="btn-group btn-block" id="cart">
<button class="btn btn-viewcart dropdown-toggle" data-loading-text="Loading..." data-toggle="dropdown" type="button" aria-expanded="false" id="cart_total"><span class="lg">My Cart</span><span><i class="fa fa-shopping-basket"></i> (<?=$_SESSION['totalitem']?>) items</span></button>
<ul class="dropdown-menu pull-right" ><li>
<table id="cart_item" class="table table-striped">
<tbody>
<?php
if(empty($_SESSION['cart'])){
?>
<tr>
<td align="center" style="font-weight: bold; font-size: 14px;" colspan="5">Your Cart Is empty</td>
</tr>
<?php
}
else{
$subtotal = 0;
foreach($_SESSION['cart'] as $key=>$value){
$subtotal = $subtotal + ($_SESSION['cart'][$key]['price']*$_SESSION['cart'][$key]['qty']);
?>
<tr>
<td class="text-center"> <img class="img-thumbnail" title="iPhone" alt="iPhone" src="../photo/<?=$_SESSION['cart'][$key]['img']?>" width="57px" height="57px">
</td>
<td class="text-left"><?=$_SESSION['cart'][$key]['name']?>
</td>
<td class="text-right">x <?=$_SESSION['cart'][$key]['qty']?></td>
<td class="text-right">$<?=$_SESSION['cart'][$key]['price']*$_SESSION['cart'][$key]['qty']?></td>
<td class="text-center"><button class="btn btn-danger btn-xs" title="Remove" onclick="cart.remove('<?=$_SESSION['cart'][$key]['id']?>','delete');" type="button"><i class="fa fa-times"></i></button></td>
</tr>
<?php
}
}
$vat= $subtotal * (20/100);
$total = $subtotal + $vat;
?>
</tbody></table>
</li><li>
<?php
if(!empty($_SESSION['cart']))
{
?>
<div>
<table class="table table-bordered">
<tbody><tr>
<td class="text-right"><strong>Sub-Total</strong></td>
<td class="text-right">$<?=$subtotal?></td>
</tr>
<tr>
<td class="text-right"><strong>Eco Tax (-2.00)</strong></td>
<td class="text-right">$2.00</td>
</tr>
<tr>
<td class="text-right"><strong>VAT (20%)</strong></td>
<td class="text-right">$<?=$vat?></td>
</tr>
<tr>
<td class="text-right"><strong>Total</strong></td>
<td class="text-right">$<?=$total?></td>
</tr>
</tbody></table>
<p class="text-right"><strong><i class="fa fa-shopping-cart"></i> View Cart</strong> <strong><i class="fa fa-share"></i> Checkout</strong></p>
</div>
<?php
}
?>
</li></ul>
</div>

Bootstrap data table search and pagination not working when data is load from ajax call

I am trying to working on bootstrap data table in Laravel. My data is load successfully but data table search and pagination is not working.so please help me.
my Html code on page is like that
<table id="example111" class="table table-striped nowrap www" cellspacing="0" width="100%">
<thead>
<tr>
<th class="col-sm-2 col-lg-1">Sr.No.</th>
<th>Department Name</th>
<th class="col-sm-3 col-lg-2">Edit/Delete</th>
</tr>
</thead>
<tbody class="departmentlist" id="departmentlist111"></tbody>
</table>
my ajax call on page like that
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
table = $('#example111').DataTable({
paging: false,
});
table.destroy();
$('#example111').DataTable({
"serverSide": true,
"ajax": {
"url": "<?= URL::to('show_department')?>",
"dataType": "json",
"type": "post",
"data":{ _token: "{{csrf_token()}}"},
"dataSrc": function (e) {
$("#departmentlist111").html(e);
}
}
});
});
</script>
my route call on page is like
Route::post('show_department','admin\DepartmentController#show_department');
my controller call
public function show_department()
{
$cartdata = '<tr>
<td class="col-sm-2 col-lg-1"> 1</td>
<td >South Indian</td>
<td class="col-sm-3 col-lg-2">
<button type="button" class="btn btn-info btn-sm"><i class="glyphicon glyphicon-edit"></i></button>
<button type="button" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
<tr>
<td class="col-sm-2 col-lg-1"> 1</td>
<td >South </td>
<td class="col-sm-3 col-lg-2">
<button type="button" class="btn btn-info btn-sm"><i class="glyphicon glyphicon-edit"></i></button>
<button type="button" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
<tr>
<td class="col-sm-2 col-lg-1"> 1</td>
<td> Indian</td>
<td class="col-sm-3 col-lg-2">
<button type="button" class="btn btn-info btn-sm"><i class="glyphicon glyphicon-edit"></i></button>
<button type="button" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
<tr>
<td class="col-sm-2 col-lg-1"> 1</td>
<td >South Indian</td>
<td class="col-sm-3 col-lg-2">
<button type="button" class="btn btn-info btn-sm"><i class="glyphicon glyphicon-edit"></i></button>
<button type="button" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>';
echo json_encode($cartdata);
}
so please solve my error please.

Resources