I got some troubles when using swal to confirm delete, I do not know how to make it work
here is my blade view file:
<form action="{{ route('user.destroy', $us->id)}}" method="post">
#method('DELETE')
#csrf
<input class="btn btn-danger" type="submit" value="Delete" />
</form>
and the script using swal
<script>
//== Class definition
var SweetAlert2Demo = function() {
//== Demos
var initDemos = function() {
$('.btn-danger').click(function(e) {
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
if (!Delete) {
e.preventDefault();
}
});
});
};
return {
//== Init
init: function() {
initDemos();
},
};
}();
//== Class Initialization
jQuery(document).ready(function() {
SweetAlert2Demo.init();
});
</script>
the version of swal is https://sweetalert.js.org not https://sweetalert2.github.io/
And I'm using route resource on laravel 5.8
thanks you!
Update in case of Loops
You should give an id to your form and then in the swal callback submit the form by using the ID
<form action="{{ route('user.destroy', $us->id)}}" method="post" id="yourFormId">
Your JS Click button is almost same. Just some small change in the Swal JS Callback Method
$('.btn-danger').click(function(e) {
var $form = $(this).closest("form"); //Get the form here.
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
console.log(Delete); //This will be true when delete is clicked
if (Delete) {
$form.submit(); //Submit your Form Here.
//$('#yourFormId').submit(); //Use same Form Id to submit the Form.
}
});
});
Use GET method instead of POST.
And no need to use button or combine anything.
Try this example,which always works with my all projects.
As
Use anchor tag, Not button
<a class="btn btn-action text-danger" title="Delete" data-toggle="tooltip" onclick="deletefunction({{$your_id}})"><i class="fa fa-trash"></i></a>
Add Script As,
<script>
var deletefunction = function(id){
swal({
title: "Are you sure you want to Delete this?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false,
preConfirm: function(result) {
window.location.href = '{{url('/your_route/delete')}}/'+id;
},
allowOutsideClick: false
});
};
</script>
Related
I have the following route defined in my web.php
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
In my blade file I have a button that when clicked displays a sweetalert to confirm deletion. This works correctly, but when the user presses the delete button instead of it going to the URL defined in Ajax it goes to an incorrect URL and logs the following error:
jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found)
Here is button code
<td class="text-center"><button type="button" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-batch-id="{{ $batch->id }}"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"
><i class="fa fa-times"></i></button>
</td>
Here is my script
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var batchId = $(this).data('batch-id');
var id = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: "DELETE",
data: {batch:batchId, contribution:id},
success: function (data) {
console.log(data);
}
});
});
});
oddly enough, refreshing the page after the error returns my session flash message from my controller's destroy function
*Note: I did add the DELETE verb to IIS, before this I was receiving:
405 (METHOD NOT ALLOWED)
Any ideas?
After two days of reading and wrenching I have a working solution:
route:
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
link html:
<a href="#" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"><i class="fa fa-times"></i></a>
jquery/ajax:
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var contributionId = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
method: "DELETE",
url: "{{ url('/contributions/contribution/destroy') }}",
data: {contributionId:contributionId},
success: function (msg) {
if ( msg.status === 'success' ) {
swal("Deleted", msg.msg, "success");
setInterval(function() {
window.location.reload();
}, 3900);
}
},
error: function(msg) {
swal("Error!", "Something went wrong.", "error");
console.log(msg.status);
}
});
});
});
</script>
controller:
public function destroy(Request $request)
{
if ( $request->ajax() ) {
Contribution::find($request->contributionId)->delete();
return response(['msg' => 'Entry deleted', 'status' => 'success']);
}
return response(['msg' => 'Failed deleting the entry', 'status' => 'failed']);
}
Works perfectly!
Try this style of ajax
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
'data':{
'_method':'delete',
'_token':'{{ csrf_token() }}',
},
'method':'post'
});
in my case I removed the error by running simple classic:
php artisan route:clear
or you can launch that remotely. Create a route and a Controller and call it via browser link:
Route::get('/b/{x}', 'for_stuff\BController#kukuku');
and put into the controller's function:
Artisan::call('route:clear');
say:
https://mysite/b/r
I'm trying to make a confirmation popup before user submits the form with CodeIgniter but the trigger/submit part is not working. It asks for confirmation but doesn't submits the form.
My HTML:
<?php
echo form_open(site_url("action"), array('id' => "order" , )) ?>
<input type="text" class="form-control" name="anything" value="">
<button type="submit" id="btn-submit" class="btn btn-danger" class="form-control">Submit</button>
<?php echo form_close() ?>
And Here's the Javascript
$('#btn-submit').on('click',function(e){
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(isConfirm){
if (isConfirm) form.submit();
});
});
I've also tried targeting/selecting form id instead button but same issue. Resources are loaded properly.
Change it:
var form = $(this).parents('form');
to
var form = $(this).parent('form');
and try again.
I was actually using wrong function. The function I used was from sweetalert while I loaded sweetalert2. I changed the code from
swal({
{... closeOnConfirm: false},
function() {
// Function
}
});
to
swal({
...
showLoaderOnConfirm: true,
preConfirm: function() {
//function
}).then(function() {
swal('Processing');
});
and it's working
I want to delete specific rows in mysql by jquery. It works on the first row, but in the second row, nothing happens.
This is my HTML code:
<td><p data-placement="top" data-toggle="tooltip" title="Delete">
<button id="dele_com" class="btn btn-danger btn-xs" name="<?php echo $rows['companyID']; ?>">
<span class="icon-trash"></span>
</button></p>
</td>
and this is my jquery code:
$("#dele_com").on("click", function(event) {
var show_id = this.name;
alert(show_id);
bootbox.dialog({
message: "Are you sure you want to Delete this account ?",
title: "<i class='icon-trash'></i> Delete !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
$.post('update_delete.php', { 'pid1':pid1 })
.done(function(response){
window.location.href= "modification.php";
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
});
Here you have specified the id #dele_com and that will be the same for every row. So when you click on the delete button it will find the first id of your table and performs click.
You have to use class selector instead of id then it will work
I'm trying to delete a row in db with Jquery / Ajax.
I have followed this thread but I can't make it working.
Here is my view:
#foreach($tournaments as $tournament)
<tr id="line" data-id="{{$tournament->id}}">
<td>
{{ $tournament->id }}
</td>
<td>{{ $tournament->owner->name}}</td>
<td class="text-center">
{!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteTourament', 'action' => ['TournamentController#destroy', $tournament->id]]) !!}
{!! Form::button( '<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ] ) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
<script>
$(function () {
$('#.tnDeleteTournament').on('click', function (e) {
var inputData = $('#formDeleteTourament').serialize();
var dataId = $('.btnDeleteTournament').attr('data-id');
console.log(inputData); // displays: _method=DELETE&_token=tGFhaAr5fVhDXEYL3SaXem3WaTNJlSdFEkaVDe9F
console.log(dataId); // displays 1
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "You will not be able to recover this Tournament!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
$.ajax(
{
type: 'POST', // I tried with DELETE too
url: '{{ url('/tournaments/') }}' + dataId,
data: inputData,
success: function (msg) {
console.log('success'); // It triggers!
$tr.find('td').fadeOut(1000, function () {
$tr.remove();
});
swal({
title: "Deleted!",
text: "Tournament has been deleted.",
confirmButtonColor: "#66BB6A",
type: "success"
});
},
error: function () {
swal("Oops", "We couldn't connect to the server!", "error");
}
}
)
}
else {
swal({
title: "Cancelled",
text: "Your Tournament is safe :)",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
});
});
Here is my contoller:
public function destroy(Tournament $tournament)
{
$tournament->delete();
return response(['msg' => 'Product deleted', 'status' => 'success']);
}
Before, I had it working without AJAX so route is OK.
Everything works fine (modals shows) but it doesn't delete my tournament
I am new to JS / JQuery, so I don't know what's going on.
Any idea how to fix it?
You need to pretty much change all your references to use class as a selector. I am only guessing on the Laravel stuff, also make your id's unique (I appended tournament Id), but it all needs to change to class:
Guessing on this, not familiar with the syntax
#foreach($tournaments as $tournament)
<tr id="line{{$tournament->id}}" data-id="{{$tournament->id}}" class="parentTr">
<td>
{{ $tournament->id }}
</td>
<td>{{ $tournament->owner->name}}</td>
<td class="text-center">
{!! Form::open(['method' => 'DELETE', 'class' => 'formDeleteTourament', 'action' => ['TournamentController#destroy', $tournament->id]]) !!}
{!! Form::button( '<i class="glyphicon glyphicon-remove"></i>', ['class' => 'btn text-warning-600 btn-flat btnDeleteTournament', 'data-id' => $tournament->id ] ) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
Javascript Changes
<script>
$(function () {
$('.btnDeleteTournament').on('click', function (e) {
var inputData = $(this).parents('.formDeleteTourament').serialize();
var dataId = $(this).data('id');
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "You will not be able to recover this Tournament!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
$.ajax({
// I don't you know if you have to escape the inner
// quotes or not, that is a framework syntax thing
url: '{{ url('/tournaments/') }}',
type: 'POST',
// Just include the id in a post data object
data: { form: inputData, id: dataId },
success: function (msg)
{
console.log(msg);
$tr.find('td').fadeOut(1000, function() {
$tr.remove();
});
swal({
title: "Deleted!",
text: "Tournament has been deleted.",
confirmButtonColor: "#66BB6A",
type: "success"
});
},
error: function()
{
swal("Oops", "We couldn't connect to the server!", "error");
}
});
}
else {
swal({
title: "Cancelled",
text: "Your Tournament is safe :)",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
});
});
</script>
I can't seem to make this to work. I'm trying to submit form using jquery dialog and I want to receive in php so I can use $_POST.
Any idea?
HTML:
<div id="table_rows_form">
<form id="fieldsform" action="system/create">
<label for="fields">How many fields are needed?</label>
<input type="text" id="fields" name="fields" />
<button type="submit">Submit</button>
</form>
</div>
Javascript:
$(document).ready(function() {
$('#table_rows').on('click', function() {
$('#table_rows_form').dialog({
open: function() {
$(this).find('[type=submit]').hide();
},
draggable: true,
modal: true,
resizable: false,
closeOnEscape: false,
width: 'auto',
minHeight: 235,
title: 'Number of Fields',
dialogClass: 'no-close',
buttons: {
"Send": function() {
$('#fieldsform').submit(function(event) {
var formData = {
'fields': $('input[name=fields]').val()
};
$.ajax({
type: 'POST',
url: $('#fieldsform').attr('action'),
data: formData,
dataType: 'json',
encode: true
});
});
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
return false;
});
});
PHP:
print_r($_POST);
The dialog opens correctly but when pressing send button doesn't do anything and doesn't gives any error at the console. Any idea about the error? I'm a newbie with jquery.
You're just adding a submit handler with your code $('#fieldsform').submit( ... ) so it doesn't trigger anything.
Rather, you should do that on document ready, and in the click handler for "Send" button, call $('#fieldsform').submit();