I am not fluent in javascript and I cannot understand very well because the .then (result) does not work for me. That is, it is never confirmed,
so, it never enters the if conditional. The code is the same as that offered in the SweetAlert api. Where does that variable result come from?
All the code of my script. Try to use Sweet alert for confirmation a delete form... No works the button confirmation in this way:
#extends('adminlte::page')
#section('title', 'Borradores')
#section('content_header')
<h1 class="text-center">Listado de borradores</h1>
#stop
#section('content')
{{-- {{ route('admin.create') }} --}}
<div class="card">
<div class="card-header">
<a class="btn btn-primary btn-block" href=""><i class="fas fa-table mr-2"></i> Crear nuevo Articulo</a>
</div>
<!-- /.card-header -->
<div class="card-body">
<table id="tablaArticulos" class="table table-bordered table-striped dt-responsive tablas">
<thead>
<tr class="text-center">
<th>Categoria</th>
<th>Titulo</th>
<th>Entradilla</th>
<th>¿Publicar?</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
{{-- {{ route('admin.destroy', $post ) }} --}}
#foreach ($posts as $post)
<tr class="text-center">
<td>{{ $post->category->name }}</td>
<td>{{ $post->name}}</td>
<td>{{ $post->extract}}</td>
<td><a class="btn btn-success" href="{{ route('admin.edit', $post) }}"><i class="fas fa-cross"></i></a></td>
<td>
{{-- {{ route('admin.edit', $post ) }} --}}
<form action="{{ route('admin.destroy', $post->id) }}" method="post" class="delete-form">
#csrf
#method('delete')
<div class="btn-group">
<a class="btn btn-warning" href="{{route('admin.edit', $post)}}"><i class="fas fa-pen"></i></a>
<button type="submit" class="btn btn-danger"><i class='fas fa-trash'></i></button>
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr class="text-center">
<th>Categoria</th>
<th>Titulo</th>
<th>Entradilla</th>
<th>¿Publicar?</th>
<th>Acciones</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
#stop
#section('css')
<style>
.fotoTabla{
width: 60px;
}
</style>
<link rel="stylesheet" href="/css/admin_custom.css">
#stop
#section('adminlte_js')
#stack('js')
#yield('js')
<script src="{{ asset('js/app.js') }}"></script>
{{-- Datatables responsive --}}
<script src="https://cdn.datatables.net/responsive/2.2.7/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.7/js/responsive.bootstrap4.min.js"></script>
{{-- id Databales --}}
<script>
$(function () {
$(".tablas").DataTable({
responsive: true,
autoWidth:false
});
});
</script>
#if (session('crear'))
<script>
Swal.fire({
title: '{{ session("crear") }}',
icon: 'success',
showConfirmButton: false,
timer: 2500,
timerProgressBar: true
})
</script>
#endif
#if (session('message'))
<script>
Swal.fire({
title: '{{ session("message") }}',
icon: 'success',
showConfirmButton: false,
timer: 2500,
timerProgressBar: true
})
</script>
#endif
#if (session('alert'))
<script>
Swal.fire({
title: 'ATENCIÓN',
text: '{{ session("alert") }}',
icon: 'warning',
showConfirmButton: false,
timer: 3500,
timerProgressBar: true
})
</script>
#endif
<script>
// Mensaje de alerta al pulsar el Botón de borrar en las tablas
$('.delete-form').submit(function(e){
e.preventDefault();
let nombreElemento = e.target.parentElement.parentElement.children[1].innerText;
console.log(nombreElemento);
Swal.fire({
title: `¿Estás seguro de borrar ${nombreElemento}?`,
text: "Recuerda que esta acción es irreversible",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#50f8ac',
cancelButtonColor: '#d33',
focusCancel: true,
confirmButtonText: 'Ok, borralo',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.isConfirmed) {
this.submit();
}
});
});
</script>
#stop
I have placed two console.log () before the .then and a else in the conditional
<script>
// Mensaje de alerta al pulsar el Botón de borrar en las tablas
$('.delete-form').submit(function(e){
e.preventDefault();
let nombreElemento = e.target.parentElement.parentElement.children[1].innerText;
Swal.fire({
title: `¿Estás seguro de borrar ${nombreElemento}?`,
text: 'Recuerda que esta acción es irreversible',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#50f8ac',
cancelButtonColor: '#d33',
focusCancel: true,
confirmButtonText: 'Ok, Bórralo',
cancelButtonText: 'Cancelar'
}).then((result) => {
console.log('Inside.. ');
if (result.isConfirmed) {
this.submit();
} else {
console.log('No confirmed!! ');
}
});
});
</script>
And selecting both buttons, I get the same result.
I make a Video with this strange behaviour
Video in drive
It comes from the dialog it pops up... If you confirm the 'Are you sure?' then it will fire next dialog 'Deleted!'.
In the end, after many days I found the solution.
I changed the version in the Adminlte configuration of the installed sweetalert. I had version eight sweetalert2#8
which comes by default and I have passed it to ten. This has fixed the strange behavior.
'Sweetalert2' => [
'active' => true,
'files' => [
[
'type' => 'js',
'asset' => false,
'location' => '//cdn.jsdelivr.net/npm/sweetalert2#10',
],
],
],
In simplest form variable result - is the result of button click... that is passed down from the Swal() to .then()
This is the simplest form of explanation I could give you, if you wish to understand this in detail you should learn more about the Promises and Asyncronise code in JS
The Code you have given in the question is working fine here is the jsfiddle link for the same Link
if you add ! before the result then the 2nd pop-up will fire when you click the cancel button and nothing will happen if you click yes button
====Update====
Change the single quotes of .fas.fa-trash to double quotes
<button type="submit" class="btn btn-danger"><i class='fas fa-trash'></i></button>
to
<button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i></button>
all Swal.fire() functions are missing ;
also there is a lot of inconsistency while using a double quote, single quotes & Template literals
Please formate the script tag.. there could be one misplaced quote that might be causing this weird behaviour...
Also in the .then() block before you call the if() console log to see what you have inside of the result.
The rest of the code is looking good there should is no issue with the syntax/code while calling Swal.fire()
Related
I have a component with version 3 of vue, what I'm trying to do is call a function of my component from the rendering of a datatable column, I just don't know if it's possible. In this case, the function that I am trying to call on the click of a button is editCredential, as it would be done in the template normally. Only this is currently not working for me. What I'm trying to avoid is defining a listener on the table and filtering until I hit the button since I don't like it that much. If anyone knows of a way to do this please help me.
export default{
data() {
return {
credentials:[]
}
},
methods: {
getCredentials(){
jQuery.ajax({
url : window.origin+"/apiadmin/credentialsincludes",
data : {opc:"credentials", action:"getCredentials"},
method : 'post',
dataType:"json",
}).then(resp=>{
this.credentials = resp;
this.generateTable();
}).fail(resp=>{
swal('Ocurrio un problema en la peticion en el servidor, favor de reportar a los administradores', {icon:'error'});
}).catch(resp=>{swal('Ocurrio un problema en la peticion en el servidor, favor de reportar a los administradores', {icon:'error'});});
},
generateTable(){
jQuery('#credenciales').DataTable( {
dom: 'Blfrtip',
data : this.credentials,
"autoWidth": true,
"scrollCollapse": true,
"searching": true,
"paging": true,
"language": {
"emptyTable": "No se encontraron solicitudes registradas"
},
scrollX:"auto",
buttons: [
{
extend: 'excel',
className: 'btn btn-default',
order: [[0, 'asc'], [5, 'asc']],
}
],
"columns": [
{ width:"5%","data": "id_key" },
{ width:"11%","data": "key" },
{ width:"10%","data": "user_key" },
{ width:"10%","data": "nombre_key" },
{ width:"12%","data": "descripcion" },
{ width:"12%","data": "nombre_unidad_negocio" },
{ width:"10%","data": "nombre_cliente" },
{ width:"10%","data": "nombre_producto" },
{ width:"10%","data": "id_key",
render(data, type, data2, key, row) {
// console.log(data, type, data2, key, row);
return (1==1) ? `
<button type="button" #click="editCredential" class="btn animated pull-up btn-warning btn-sm editCredito" data-value=''><i class="la la-edit" style="font-size:11px;"></i></button>
<button type="button" class="btn animated pull-up btn-warning btn-sm editCreditoD" data-key='' data-value=''><i class="la la-trash-alt" style="font-size:11px;"></i></button>` : '';
},
},
],
} );
},
editCredential(){
console.log("hola");
}
},
created() {
setTimeout(() => {
this.getCredentials();
}, 500);
},
components:{
},
template:/* html */`
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-md-2 mb-2">
<button type="button" class="btn btn-block btn-success text-white btn-sm">
Agregar Credenciales <i class="la la-plus"></i>
</button>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-1">
<table class="table table-sm table-striped" style="width:100%;font-size:10px;" id="credenciales">
<thead>
<tr>
<th class="credentials-th">ID</th>
<th class="credentials-th">KEY</th>
<th class="credentials-th">USER</th>
<th class="credentials-th">NOMBRE</th>
<th class="credentials-th">DESCRIPCION</th>
<th class="credentials-th">UNIDAD DE NEGOCIO</th>
<th class="credentials-th">CLIENTE</th>
<th class="credentials-th">PRODUCTO</th>
<th class="credentials-th">ACCIONES</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
`
}
i working with version vue3 and i have segmented for components
here’s my problem:
I’m making a client system in javascript and php.
I would like to be able to delete the account of a customer who has a unique identifier (id=x) by clicking on a “Delete Customer” button.
<div class="menu-item px-5">
<a id="kt_account_delete_account_btn" class="menu-link text-danger px-5"> Delete Customer</a>
</div>
The problem is that to bring a little dynamism, I treat the request in javascript in this way:
submitButton.addEventListener('click', function (e) {
e.preventDefault();
swal.fire({
text: "Êtes vous sûr de vouloir supprimer ce compte ?",
icon: "warning",
buttonsStyling: false,
showDenyButton: true,
confirmButtonText: "Oui",
denyButtonText: 'Non',
customClass: {
confirmButton: "btn btn-light-primary",
denyButton: "btn btn-danger"
}
}).then((result) => {
if (result.isConfirmed) {
$.post("details.php?id="+$("#admin_id_two").val()+"&client="+$("#client_idbis").val(), $("#delete_form").serialize()) // Code I usually use in a form
.done(function(data) {
if (data.erreur)
{
Swal.fire({
text: data.erreur,
icon: "error",
buttonsStyling: false,
confirmButtonText: "Ok, je recommence!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else if (data.link)
{
Swal.fire({
text: "Le compte utilisateur a correctement été supprimé !",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Ok, je continue!",
customClass: {
confirmButton: "btn btn-primary"
}
}).then(function (result) {
if (result.isConfirmed) {
window.location.href = data.link;
}
});
}
})
.fail(function() {
Swal.fire({
text: "Une erreur est survenue lors de la requête. Veuillez ré-essayer.",
icon: "error",
buttonsStyling: false,
confirmButtonText: "Ok, je recommence!",
customClass: {
confirmButton: "btn btn-primary"
}
});
});
} else if (result.isDenied) {
Swal.fire({
text: "Vous n'avez pas supprimer le compte de l'utilisateur.",
icon: 'info',
confirmButtonText: "Ok",
buttonsStyling: false,
customClass: {
confirmButton: "btn btn-light-primary"
}
})
}
});
});
My request is as follows:
I would like to recover the customer id ($clientinfo[‘id’] in php) and the administrator id ($login[‘id’] in php) in javascript to execute the request.
Could you help me?
add attribute data-id your a tag
like this:
<a id="kt_account_delete_account_btn" data-id="12" class="menu-link text-danger px-5"> Delete Customer</a>
remember: 12 is example, you should load id dynamically by php
and get in your Listener . like this:
submitButton.addEventListener('click', function (e) {
e.preventDefault();
let id = this.getAttribute('data-id');
Assuming variable $userID contains the ID of the user, you can append user id to data-id attribute using php as shown then use Javascript to get the data-id attribute as pointed out by Ali SSN. See using Jquery in snippet
<a id="kt_account_delete_account_btn" data-id="<?php echo $userID;?>" class="menu-link text-danger px-5"> Delete Customer</a>
$(document).on('click','.menu-link',function(e){
e.preventDefault();
var userID=$(this).attr('data-id');
alert(userID);
})
a{
color:blue;
text-decoration:underline;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu-item px-5">
<a id="kt_account_delete_account_btn" class="menu-link text-danger px-5"data-id="5"> Delete Customer</a>
</div>
So I have run into a bug that is just driving me crazy. When you open my webpage, a list of jobs are provided which have a small heart shaped wishlist icon next to them. Normally, if the job is part of your wishlist it should appear as a red icon, which if you click would have a sweetalert popup that says the job is removed from your wishlist. And if the job is not part of your wishlist it would be displayed in blue, which if you click would have a pop up that says the job has been added to your wishlist. All this works, except for when you have just loaded the page for the first time, and one of the listed jobs is NOT part of your wishlist, and displayed in blue. If you click this blue icon, instead of saying "added to wishlist" and turning red, it says "removed from wishlist" and stays blue, even though its not part of the wishlist. Clicking the button AGAIN, will then do the correct action, saying "added to wishlist" and flipping the color, so the error only occurs the first time. Something wrong with .data('wl') being set for the first time?
But the funny part is, if you load the page for the first time and one of the jobs IS part of your wishlist and displayed in red, clicking it will do the correct action, giving a popup saying it has been removed, and turning the wishlist icon blue - so this error ONLY occurs on the first attempt to turn a BLUE icon RED. Any subsequent attempt works fine unless you refresh the page. The error never occurs when clicking a wishlisted(RED) job turning it blue, even on the first attempt.
Side Note: Please keep in mind I am trying to change the color of the wishlist icon without reloading the page. I've also included an image for context. Thanks!
Image of job listing page with wishlist icons, red=Remove, blue=Add
function addorremove(id) {
if (id){
var wishlist= $('#jobwl'+id).data('wl');
if (wishlist == 0) {
$.ajax({
url:"/users/add-wishlist/" +id,
method:"GET",
success:function () {
$('#jobwl'+id).removeClass('btn-primary').addClass('btn-danger')
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: true,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Added to Wishlist'
})
$('#jobwl'+id).data('wl',1);
}
});
}else{
$.ajax({
url:"/users/remove-wishlist/" +id,
method:"GET",
success:function () {
$('#jobwl'+id).removeClass('btn-danger').addClass('btn-primary')
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: true,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Removed from Wishlist'
})
$('#jobwl'+id).data('wl',0);
}
});
}
}
}
<div class="ml-auto d-flex">
Apply Job
{% if job.id in wish_list %}
<a href="javascript:void(0);" id="jobwl{{ job.id }}" title="Remove from my wishlist" onclick="addorremove({{ job.id }})" class="btn btn-danger rounded-circle btn-favorite d-flex align-items-center">
<span class="icon-heart"></span>
</a>
{% else %}
<a href="javascript:void(0);" id="jobwl{{ job.id }}" title="Add to my wishlist" onclick="addorremove({{ job.id }})" class="btn btn-primary rounded-circle btn-favorite d-flex align-items-center">
<span class="icon-heart"></span>
</a>
{% endif %}
</div>
I am building a web application using Laravel 5.8. I have started to dive into using JQuery and it's amazing. However, I have not been able to find an answer to my issue. Hoping someone can help.
I have a view named "roles" and it is responsible for showing a list of the security-based roles on the system. On that view, I have a data table displaying that list of roles, date created, and so forth. There is a column for "Permissions" on that data table. Where previously I would put the list of permissions assigned with that role. If you look at my previous code, I was able to achieve that. I have not been able to figure it out with Jquery.
The previous view code:
#foreach ($roles as $role)
<tr>
<td>{{ $role->name }}</td>
<td>
#if($role->name === "superadmin")
<span class="badge badge-primary">All Permissions</span>
#else
#foreach($role->permissions()->pluck('permission_name') as $permission)
<span class="badge badge-primary">{{ $permission }}</span>
#endforeach
#endif
<td nowrap>#if($role->name != "superadmin")<span class="dropdown">
<a href="#" class="btn btn-sm btn-clean btn-icon btn-icon-md" data-toggle="dropdown" aria-expanded="true">
<i class="la la-ellipsis-h"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="{{ route('admin.security.roles.edit',$role->id) }}"><i class="la la-edit"></i> Edit Role</a>
<a class="dropdown-item" href="javascript:delete_role('{{ $role->id }}');"><i class="la la-remove"></i> Delete Role</a>
</div>
</span>
#endif
</tr>
#endforeach
The previous controller code:
public function index()
{
$roles = Role::all();
return view('backend.auth.roles.index')->with('roles', $roles);
}
The current php code:
public function index()
{
$permission = Permission::get();
if(request()->ajax()) {
return datatables()->of(Role::all())
->addColumn('actions', 'layouts._partials.backend._crud-default')
->rawColumns(['actions', 'permissions'])
->addIndexColumn()
->make(true);
}
return view('site.backend.auth.roles.index', compact('permission'));
}
The current view code:
<!--begin: Datatable -->
<table class="table table-striped- table-bordered table-hover table-checkable" id="roles_table">
<thead>
<tr>
<th>Name</th>
<th>Permissions</th>
<th>Created</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
</table>
<!--end: Datatable -->
The current javascript code:
$(document).ready( function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#roles_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('admin.security.roles.index') }}",
type: 'GET',
},
columns: [
{data: 'name'},
{data: 'permissions'},
{data: 'created_at'},
{data: 'updated_at'},
{data: 'actions', name: 'action', orderable: false},
],
order: [[0, 'name']],
});
});
The error message is showing the obvious and that $role and $permission variables are not present.
Currently I am working on a page with Bootstrap tables. These tables are autofilled. On the first page there are no problems to eliminate an element, because there is a confirmation message to eliminate.
When I go to the next page, and I want to eliminate the click on the "x" to eliminate it makes the action of deleting, but no confirmation message appears.
Here is the code
can('delete', $unit)
<form id="{{ $unit->id }}" style="display: inline-block;" method="post" action="{{ url("estates/$estate->uid/units/$unit->uid") }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="delete">
<button id="deleteUnit-{{ $unit->id }}" class="btn btn-simple btn-danger eliminar" rel="tooltip" data-placement="left" title="Eliminar" name="eliminar" data-id="{{ $unit->id }}">
<i class="fa fa-times"></i>
</button>
</form>
#endcan
and
$().ready(function(){
window.operateEvents = {
'click .edit': function (e, value, row, index) {
info = JSON.stringify(row);
// swal('You click edit icon, row: ', info);
console.log(row.actions);
},
'click .remove': function (e, value, row, index) {
console.log(row);
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
});
}
};
$table.bootstrapTable({
toolbar: ".toolbar",
showRefresh: false,
search: true,
showToggle: false,
showColumns: true,
pagination: true,
searchAlign: 'left',
pageSize: 10,
clickToSelect: false,
pageList: [10, 15, 20],
formatShowingRows: function(pageFrom, pageTo, totalRows){
$(window).resize(function () {
$table.bootstrapTable('resetView');
});
//do nothing here, we don't want to show the text "showing x of y from..."
},
formatRecordsPerPage: function(pageNumber){
return pageNumber + " rows visible";
},
icons: {
refresh: 'fa fa-refresh',
toggle: 'fa fa-th-list',
columns: 'fa fa-columns',
detailOpen: 'fa fa-plus-circle',
detailClose: 'fa fa-minus-circle'
}
});
//activate the tooltips after the data table is initialized
$('[rel="tooltip"]').tooltip();
$(window).resize(function () {
$table.bootstrapTable('resetView');
});
$('[id^="deleteUnit-"]').on('click', function (e) {
event.preventDefault();
var id = $(this)[0].getAttribute('data-id');
swal({
title: '¿Estás seguro?',
text: "No es posible deshacer esta acción!",
type: "warning",
showCancelButton: true,
cancelButtonText: "Cancelar",
confirmButtonClass: "btn btn-info btn-fill",
confirmButtonText: "Si, eliminar",
cancelButtonClass: "btn btn-danger btn-fill",
closeOnConfirm: false,
closeOnCancel: true
}, function(isConfirm){
if (isConfirm){
document.getElementById(id).submit();
}
});
});
});
Here is an imageScreenshoot