I'm working with Laravel v8 and Sweet Alert v2 and I wanted to show a popup message when the user clicks on the Delete button.
So I coded this:
$(document).on('click', '#btn-submit', function(e) {
e.preventDefault();
let form = $(this).parents('form');
Swal.fire({
title: "Confrimation!",
text: "Are you sure you want to delete [this] user",
type: "warning",
allowEscapeKey: false,
allowOutsideClick: false,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
showLoaderOnConfirm: true,
closeOnConfirm: false
}).then((isConfirm) => {
if (isConfirm.value === true) {
document.getElementById("delForm").submit();
return true;
}
return false;
});
});
So this works fine and whenever I click on Delete button for a user, a popup message comes up and requires me to confirm or cancel the process.
But I wanted to show the username as well in the text
property of Swal (replace it with [this]
).
So the final text
would be something like this:
Are you sure you want to delete {{ $user->name }} user
Here is the form:
<div >
<table >
<tbody>
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Actions</th>
</tr>
@if($users->count() != 0)
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
@if($user->isSameUser($user->id))
<td >
<div >
<form id="delForm" action="{{ route('admin.users.destroy' , ['user' => $user->id]) }}" method="POST">
@csrf
@method('DELETE')
<input id="btn-submit" type="submit" value="Delete"></input>
</form>
</div>
</td>
@endif
</tr>
@endforeach
@else
<td colspan="10" >Nothing to show!</td>
@endif
</tbody>
</table>
</div>
But don't know how to send the username ({{ $user->name }}
) to the sweet alert message in order to show it in the text of Swal
.
In fact, I tried testing this:
Swal.fire({
title: "Attention!",
text: "{!! isset($user) ? json_decode($user->id) : '' !!}",
...
But didn't output anything, meaning that $user
is not defined!
So what's going wrong here? How can I get the data from Laravel and show it on Sweet Alert popup message?
CodePudding user response:
You can pass the user name to submit the input with data attribute
<input id="btn-submit" type="submit" data-name="{{ $user->name }}" value="Delete" />
in submit function, you get the value of data attribute like:
$(document).on('click', '#btn-submit', function(e) {
e.preventDefault();
let name = $(this).data('name');
Swal.fire({
title: "Confrimation!",
text: `Are you sure you want to delete ${name} user`,
...
Or you can pass PHP variable to javascript variable Inside submit function listener
let name = "{{ $user->name }}"
CodePudding user response:
try storing value of php variable into javascript variable
<script>
var messageTxt = "<?= isset($user) ? json_decode($user->id) : '' ?>"
Swal.fire({
title: "Attention!",
text: messageTxt,
})
</script>