I am writing a project in laravel, at my current point in the workflow I want the user to be able to click a button to publish or remove an event from the current list.
I am using SA2 to stop the submission to the route before it happens, if the user hits OK, then everything goes as planned, when the user hits cancel, I want to redirect back to the page.
The issue I am running in to is that when the user hits cancel, the redirect to the page happens anyway...
function warnRemove(linkURL) {
swal({
title: 'Are you sure?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: 'D6B55',
confirmButtonText: 'Yes, remove it!'
}).then(function () {
window.location = linkURL;
});
}
function warnPublish(linkURL) {
swal({
title: 'Are you sure?',
type: 'warning',
text: 'This event will go live on the screen after next refresh.',
showCancelButton: true,
confirmButtonColor: 'D6B55',
confirmButtonText: 'Yes, publish it!'
}).then(function () {
window.location = linkURL;
});
}
$('.remove').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
let linkURL = $(this).attr("href");
warnRemove(linkURL);
});
$('.publish').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
let linkURL = $(this).attr("href");
warnPublish(linkURL);
});
You will need to use the callback with an isConfirm boolean:
function(isConfirm) {
if (isConfirm) {
// do confirmed things
}
}
From the docs:
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
// redirect only if true
if (result.value) {
// redirect here
}
})
Related
i'v been searching for 2 days and i didint find an answer , so i made a function to delete a property onclick using ajax. but i have a weird probleme i must click twice on the button to work , i dont know why here is my code :
here is my button :
<a style="cursor: pointer"
id="{{ $i->id }}"
data-name="client/{{ Auth::guard('client')->user()->id }}/proprety"
class="delete tooltip left"
title="Supprimer">
<i class="icon-feather-trash-2"></i>
</a>
and here is my script :
$('table').on('click', '.delete', function() {
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then(function(result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
UPDATE : the first button trigger sweetalert , after i confirm on sweetalert for the first time nothing happen , i need to repeat the process and trigger sweetalert again to work
UPDATE 1 : This is my controller to delete property :
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Proprety $proprety
* #return \Illuminate\Http\Response
*/
public function destroy($proprety){
$proprety = Proprety::find($proprety);
Image::where('proprety',$proprety->unique)->delete();
Promotion::where('proprety',$proprety->id)->delete();
$proprety->delete();
return 1;
}
You have to click twice because of the way you wrapped the javascript.
Instead of writing this: $('table').on('click', '.delete', function() { ...
you should write this:
$(document).ready( function() {
$(document).on('click', '.delete', function(){ ...
So your new JS syntax should be
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then((result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
});
EDIT:
here are the syntaxes for done() and fail() functions of sweetalert:
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var url = "{{ route('delete-susomething', ':id') }}";
url = url.replace(':id', id);
var el = this;
var name = $(this).attr('data-name');
Swal.fire({
title: 'Are you sure? <h6>(Page closes in 10 seconds)</h6>',
html: "Blah Blah",
icon: 'warning',
timer: 10000,
showCancelButton: true,
confirmButtonColor: 'green',
cancelButtonColor: '#d33',
confirmButtonText: 'Go ahead',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.value){
$.ajax({
url: url,
type: 'POST',
data: {'_method':'DELETE', '_token': '{{ csrf_token() }}'},
dataType: 'json'
})
.done(function(response){
swal.fire('Oh Yeah!', "Successfully Deleted.", response.status);
})
.fail(function(){
swal.fire('Damn!', 'Beats me, but something went wrong! Try again.', 'error');
});
}
})
});
});
now in your controller that deletes the item, after deleting, you need to return a response, so add return 1; at the end of the function that handles the deletion.
So, I'm having some problem with sweetalert2 (I'm new here).
I have this script and i don't know how to make to be with progress step (see the .gif below)
Set Premium Points</li>
<script>
function givepptoplayer() {
swal({
title: 'Change User Premium Points <?php echo $data->name ?>',
input: 'number',
showCancelButton: false,
confirmButtonText: 'edit',
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger m-l-10',
allowOutsideClick: false,
inputValue: '',
}).then(function (result) {
$.post('<?php echo config::$_PAGE_URL ?>api/finishthis', { 'userid' : '<?php echo $data->id ?>', 'changePP': result.value}, function(result)
{
swal({
type: 'success',
title: 'Succes!',
html: result
});
});
});
}
</script>
I want when to make a progressStep something like here: https://gyazo.com/41f65065108e3937e3afc2a3064ee028
Can you guys give me an example please?
There is an example of chaining modals with related code on https://sweetalert2.github.io/#chaining-modals. Basically the code is:
swal.mixin({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3']
}).queue([
{
title: 'Question 1',
text: 'Chaining swal2 modals is easy'
},
'Question 2',
'Question 3'
]).then((result) => {
if (result.value) {
swal({
title: 'All done!',
html:
'Your answers: <pre><code>' +
JSON.stringify(result.value) +
'</code></pre>',
confirmButtonText: 'Lovely!'
})
}
})
Busy learning Laravel and a bit (very) confused.
I have a page with datatable and a button to delete a record.
I want this button to delete the record with ajax.
My js code:
$(document).on('click', '.deleteBtn', function() {
var url = $(this).attr('href');
swal({
title: "Are you sure?",
text: "You will not be able to recover this business type file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel pls!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax ({
url: url,
type: 'DELETE',
success: function () {
swal("Deleted!", "Your business type has been deleted.", "success");
}
});
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
return false;
});
In the Routes/api.php file:
// business type
Route::delete('businessTypes/{business_type_id?}/destroy', ['as' => 'businessTypes.destroy', 'uses' => 'BusinessTypeController#destroy']);
Route::any('businessType', 'ApiBusinessTypeController#businessTypeData', ['except' => ['destroy']]);
In Routes/web.php:
Route::get('businessTypes/create', ['as' => 'businessTypes.create', 'uses' => 'BusinessTypeController#create']);
Route::get('businessTypes/{business_type_id}-{slug?}', ['as' => 'businessTypes.show', 'uses' => 'BusinessTypeController#show']);
Route::resource('businessTypes', 'BusinessTypeController', ['except' => ['show', 'create', 'destroy']]);
When I click the delete button I get the error: 404 Page not Found.
What am I doing wrong?
I use sweetalert to get confirm for delete rows from user, the code for confirmation is
$('.delete').click(function(){
var formClass = $(this).attr('id');
$("form."+ formClass).submit(function( event ){
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
}, function() {
form.submit();
});
} else {
swal("Cansel", "Not deleted :)", "error");
}
});
});
});
and this code for use pjax to have an ajax request in laravel
$(document).on('pjax:send', function() {
$('#loading').show();
$("#pjax-container").css({"opacity": "0.3"});
})
$(document).on('pjax:complete', function() {
$('#loading').hide();
$("#pjax-container").css({"opacity": "1"});
})
$(document).on('submit', 'form[form-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
});
And the html form is:
<form action="{{ route('admin.comments.destroy',[$comment->id]) }}" class="inline-div comment-{{ $comment->id }}" method="post" form-pjax>
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-danger btn-opt delete" id="comment-{{ $comment->id }}"><span class="glyphicon glyphicon-trash"></span></button>
By this code i haven't an ajax request.
Instead of "form.submit();" What to write?
From what I can see, you don't need to use pjax for this at all. You can delete a record from database asynchronously, simply using an ajax request. Here is how I would go about doing this:
In the code below, when the user clicks on the delete link, an alert would be presented to him. If he confirms the delete action, then the function deleteFromDB would be called which is responsible for sending an ajax request to the server.
$('.delete').click(function(){
var formClass = $(this).attr('id');
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
deleteFromDB(formClass);
} else {
swal("Cancel", "Not deleted", "error");
}
});
});
The mentioned function is defined as below:
function deleteFromDB(formClass) {
var url = "http://example.com/delete/this/record";
var form = $("form."+ formClass);
var formData = new FormData();
form.find("input[name]").each(function(index, input) {
formData.append(input.name, input.value);
});
$.post(url, formData).done(function(data) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
});
});
}
It finds all the inputs that have a name attribute and appends each to a FormData object. Then a post ajax request is sent to the server and when the request is done, another alert showing the success of deletion shows up.
Pay attention here not to show the success alert before deleting the record (as you were doing in the above code), because then if something goes wrong during the request, i.e. the record could not be deleted for some reason, you would be able to show that error to the user.
I want to delete the record using sweetalert js.
This is my view file:-
<a class="action-link delete" title="delete" href="#" onclick="confirmDelete()"> <i class="glyphicon glyphicon-trash"></i> </a>
This is my function:-
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: base_url+"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
This is my controller delete function
public function delete(){
$id = $this->input->post('id');
$data[ 'status'] = '0';
$where = array( 'id' => $id );
$this->model->update( $this->tablename , $data , $where );
}
But not delete the data. Please help me out.
Edit: url as below
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: <?=base_url()?>"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}