jQuery: hide table row - php

This is the function that is called when button delete is pressed. After confirmation of delete, I want to hide the delete tr :
function delete_confirmation(id) {
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "To delete this patient!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: localStorage.getItem("base_url") + '' + 'index.php/Patient_ws/delete/',
timeout: 4000,
type: "POST",
data: ({id: id}),
}).done(function () {
$tr.remove();
})
.fail(function () {
swal({
title: ' erreur in server, try later...',
type: 'warning'
})
})
} else {
swal("Patient not deleted");
}
});
}
Html markup:
<a href="#" class="btn btn-danger btn-xs" onclick="delete_confirmation(<?php echo $patient->id_personne;?>)">
<i class="fa fa-trash-o"></i> Delete </a>
I want to hide tr - please help.

There is no explicit this in an onclick function unless you pass it in from the html. Try console.log(this) will see it is probably Window and not the element
Since you are already using jQuery I would suggest also using it for the event listener and moving the php output to a data attribute
HTML
<a class="delete-row-btn btn btn-danger btn-xs"
data-id="<?php echo $patient->id_personne;?>">
JS
$(document).on('click','.delete-row-btn', delete_confirmation)
function delete_confirmation(event) {
event.preventDefault();
// now `this` is the button
var id = $(this).data('id')
var $tr = $(this).closest('tr');
// all else should be same
swal({
.....
}

Related

Delete Image through Ajax without reloading page laravel

I want to delete Image without reloading a page through Ajax but every time when I delete the Image, first it's not deleted but when I refresh the page the image can delete.
app.js:
$('.delete-image').on('click', function(e){
e.preventDefault();
let id = $(this).attr('data-id');
bootbox.confirm("Are you sure you want to delete this company?", function(result){
if(result){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'DELETE',
url : '/albums/delete',
data : {
id : id,
},
success : function(response){
if(response){
$(this).parents('.album').slideUp().remove();
}
}.bind(this)
})
}
}.bind(this));
});
AlbumController:
public function deleteImage(Request $request){
$album = Album::find($request->id);
if($album->delete())
return response()->json(true);
else
return response()->json(false);
}
blade.php:
#extends('layout.app')
#section('content')
<div class='medium-3 columns end'>
<div class="row text-center">
#foreach($album as $albm)
<h4>{{$albm->name}}</h4>
<h4>{{$albm->description}}</h4>
<a href="/albums/{{$albm->id}}" class="btn btn-link">Edit
<img class="thumbnail" src="/storage/store/{{$albm->cover_image}}" alt="{{$albm->name}}">
</a>
Delete
<br>
#endforeach
</div>
</div>
#endsection
Route:
Route::delete('/albums/delete', 'AlbumController#deleteImage');
$(this).parents('.album').slideUp().remove();
You have no elements with class="album" so the selector won't match anything.
After delete success response just delete its parent div that has class row
$('.delete-image').on('click', function(e){
e.preventDefault();
let id = $(this).attr('data-id');
let parentDiv = $(this).closest('div.row');
bootbox.confirm("Are you sure you want to delete this company?", function(result){
if(result){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'DELETE',
url : '/albums/delete',
data : {
id : id,
},
success : function(response){
if(response){
$(parentDiv).remove();
}
}.bind(this)
})
}
}.bind(this));
});

Datatable remove row on mobile

I use laravel with datatable to display large data table.
I have a delete button at the end of each row to delete record from my database.
I use ajax and if it's a success I remove the row.
It work well on desktop but it doesn't work on mobile (except if I set computer version).
Here my table :
<table class="datatable table table-striped- table-bordered table-hover table-checkable" id="m_table_1">
<thead>
<tr>
<th>Numéro</th>
<th>Bâtiment</th>
<th>Nature</th>
<th>Options</th>
</tr>
</thead>
</table>
My js to load data :
var table = $('.datatable').DataTable({
responsive: true,
ajax: '{{ route('lots.clientSide') }}',
deferRender: true,
scrollY: '500px',
scrollCollapse: true,
scroller: true,
stateSave: true,
select: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.10.16/i18n/French.json",
select: {
rows: "%d éléments sélectionnés"
}
},
columns: [
{ data: 'id' },
{ data: 'batiment.nom', defaultContent: "----" },
{ data: 'nature' },
{ data: null }
],
columnDefs:[
{targets:-1,title:"Options",width: "10%",orderable:!1,render:function(a,t,e,n){
var slug = e.id;
var url = 'show';
var url_delete = "lots/delete/"+e.id;
return '\n<a href="'+url+'" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="View">\n'+
'<i class="la la-eye"></i>\n'+
'</a>'+
'<span class="dropdown">\n'+
'<a href="#" class="btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="dropdown" aria-expanded="true">\n'+
'<i class="la la-ellipsis-h"></i>\n'+
'</a>\n'+
'<div class="dropdown-menu dropdown-menu-left">\n'+
'<a class="dropdown-item" href="#"><i class="la la-edit"></i> Editer</a>\n'+
'<button class="delete dropdown-item" data-href="'+url_delete+'"><i class="la la-trash"></i> Supprimer</button>\n'+
'</div>\n'+
'</span>\n'
}}
]
});
And my code for the remove :
$(document).on('click', '.delete', function(e){
var $this = $(this);
table.row($this.parents('tr')).remove().draw(false);
alert("click");
$.ajax({
type: 'GET',
url: $this.data('href'),
dataType: 'json',
success: function( data ) {
},
error: function(xhr, status, error) {
alert("fail");
}
})
});
I tried with debug tools on computer and I've got nothing on console.
If I use the function on computer, it work. But if I reduce size of the windows, it doesn't work under a certain size.
Is it normal ? Can I do something about it ?
Thank
I manage to avoid this problem by not hidding delete button on mobile.

JQuery not replacing table row after edit

I'm working on a laravel app, and I'm performing CRUD with JQuery Ajax. What happens is that when I try to first edit a record after insertion or page reload it works fine. But if I try to edit that record which have just been edited, the edit works but the changes isn't shown on the page or that particular row isn't replace.
To accomplish this I'm assigning every row a unique id when record is inserted into the table. This is how my code looks:
Table:
<tbody id="subjects">
#foreach($subjects as $subject)
<tr id="row{{$subject->id}}">
<td>{{$subject->name}}</td>
<td>{{$subject->level}}</td>
<td>
<a data-id="{{$subject->id}}" data-name="{{$subject->name}}" data-level="{{$subject->level}}" data-toggle="tooltip" title="Edit" id="edit-modal" href="#" role="buton">
<i class="glyphicon glyphicon-edit text-info"></i>
</a>
</td>
<td>
<a id="delete" data-id="{{$subject->id}}" data-toggle="tooltip" title="Delete" href="#" role="button">
<i class="glyphicon glyphicon-trash text-danger"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
Script to insert record:
$(".box-footer").on('click', '.add-subject', function(event) {
event.preventDefault();
/* Act on the event */
var name = $('#name').val();
var level = $('#level').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/subjects",
data: {name: name, level: level},
success: function(data) {
if (data.errors) {
$('.errors').removeClass('hidden');
var errors = '';
for(datum in data.errors){
errors += data.errors[datum] + '<br>';
}
$('.errors').show().html(errors); //this is my div with
} else {
$('#subject-modal').modal('hide');
var html;
html += '<tr id="row"'+data.id +'">';
html += '<td>'+data.name+'</td>';
html += '<td>'+data.level+'</td>';
html += '<td><a id="edit-modal" data-id="'+data.id+'" data-name="'+data.name+'" data-level="'+data.level+'" data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a></td>';
html += '<td><a id="delete" data-id="'+data.id+'" data-toggle="tooltip" title="Delete" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a></td>';
html += '</tr>';
$("#subjects").append(html);
}
},
error: function(data) {
// body...
$('#subject-modal').modal('hide');
// display error
$('.errors').removeClass('hidden');
$('.errors').text('Ooops! There was an error. Please try again, and if error persits contact administrator');
}
});
});
Script to edit record:
$(".box-footer").on('click', '.edit-subject', function(event) {
event.preventDefault();
/* Act on the event */
// id of the row to be deleted
var id = $('#id').val();
var name = $('#name').val();
var level = $('#level').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/subjects/update/'+id,
type: 'PUT',
data: {name: name, level: level},
success: function (data) {
// body...
if (data.errors) {
var errors = '';
for(datum in data.errors){
errors += data.errors[datum] + '<br>';
}
// removing the errors class and displaying errors
$('.errors').removeClass('hidden');
$('.errors').show().html(errors);
} else {
$('#subject-modal').modal('hide');
var html;
html += '<tr id="row"'+data.id +'">';
html += '<td>'+data.name+'</td>';
html += '<td>'+data.level+'</td>';
html += '<td><a id="edit-modal" data-id="'+data.id+'" data-name="'+data.name+'" data-level="'+data.level+'" data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a></td>';
html += '<td><a id="delete" data-id="'+data.id+'" data-toggle="tooltip" title="Delete" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a></td>';
html += '</tr>';
$('#row'+data.id).replaceWith(html);
console.log(data);
}
},
error: function(data) {
// display error
$('.errors').removeClass('hidden');
$('.errors').text('Ooops! There was an error. Please try again, and if error persits contact administrator');
}
});
});
Am I missing something in my code? Are there better ways I can do this? Please Help!
I suggest you do it as following:
Give each input a unique id, ex: id="name{{$subject->id}}".
The edit function should pass variable [ID] in your edit button like this: onclick="editModel({{$subject->id}});"
On function the code should work as following:
function editModel(id){
var name = $('#name'+id).val();
....
}
Now you can select each input with ease.
also you can send data including [ID] to edit in your backend.
Table is not not reachable by DOM when created after DOM ready, so you should give each input and Id to select.

How to Select Custom line AJAX in Laravel

My problem is that when I delete a line we can only do I delete a row and jQuery practice for other lines will not be executed.
<script>
$('#destroy').on('click', function (e) {
e.preventDefault();
var token = $('input[name="_token"]').attr('value');
var id = $('#destroy').data("id");
$.ajax(
{
url: "{{ url('/category') }}" + '/' + id + '/delete',
type: 'post',
dataType: "JSON",
data: {"id": id, '_token': token},
success: function (data) {
alert(data.msg)
}
});
console.log("It failed");
});
</script>
line:
<tr id="destroy_">
<td>
<a id="destroy" data-id="{{$cat->id}}" href="#">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
<td>
<a href="{{action('categoryController#update',[$cat->id])}}">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
</td>
<td>
<a href="{{action('categoryController#show', [$cat->id])}}">
{{$cat->category}}
</a>
</td>
<th class="text-right">{{$cat->id}}</th>
</tr>
Using ID's for actions that are repeated in a table is a bad idea if you don't name them dynamically. Either way I suggest using anything other than an ID, for example a custom data attribute. So use this for your delete links:
<a data-delete data-id="{{$cat->id}}" href="#">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
And in your JS code instead of #destroy you can now use the following selector to match them:
$(document).on('click', '[data-delete]', function (e) {
e.preventDefault();
var token = $('input[name="_token"]').attr('value');
var id = $(this).data("id");
$.ajax(
{
url: "{{ url('/category') }}" + '/' + id + '/delete',
type: 'post',
dataType: "JSON",
data: {"id": id, '_token': token},
success: function (data) {
alert(data.msg)
},
error: function () {
// Also the failed request should be handled here
// not below the ajax call because it's asynchronous
console.log("It failed");
}
});
});

Symfony delete ajax

I have a problem when I want delete a register with Ajax and Symfony, in template Twig.
<tbody>
{% for entity in entities %}
<tr>
<td>
<a class="delete btn btn-danger btn-xs glyphicon glyphicon-trash" data-playgroup-id="{{ entity.id }}" ></a>
</td>
</tr>
{% endfor %}
</tbody>
Ajax:
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
if(result){
$.ajax({
url: '{{path('playergroup_delete', { 'id': pid}) }}',
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
I receive the next error:
Variable "pid" does not exists.
Thanks!
As MouradK say you ar passing a variable in a twig function (server side) and you are getting this variable using javascript (client side).
to solve this do something like this :
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
url = '{{path('playergroup_delete', { 'id': 0}) }}';
url = $url.replace("0",pid);
if(result){
$.ajax({
url: url,
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
It means that you did not pass the pid variable to your Twig template.
Pass it trough the controller and you'll be fine
The error is :
You are trying to set a variable comming from the client (javascript) in your twig template (which is a server side).

Categories