How to use Sweet Alert to send ajax DELETE request in Rails? - javascript

Problem 1: When I click the link, the sweet alert modal pops up for a split second, disappears, and redirects to route. Not sure why the modal is only flashing when it should stay until option chosen. I need user to confirm yes or no to delete account. If no then cancel, if yes than redirect to route.
Problem 2: I also understand from looking at this doc that in order to use the DELETE method in Sweet Alert I have to use an ajax request. Not sure what to put in url since I am using a rails route with a DELETE method, in order to get the ajax to redirect to that route to delete account.
Any help appreciated. Been working on this two days now.
Edit: Rails version 4.2.4, Sweet Alert version 1
<%= link_to 'Delete Account',registration_path(current_user), method: :delete, data: { behavior: 'delete' } %>
$("[data-behavior='delete']").on('click', function (e) {
e.preventDefault();
swal ({
title: 'Are you sure?',
text: 'You will not be able to recover your account!',
icon: 'warning',
buttons: [ 'Yes', 'No']
}).then(isNo => {
if(isNo) return;
$.ajax({
url: $(this).attr('href'),
dataType: "JSON",
method: "DELETE",
success: ()=> {
swal('Deleted!', 'Your account has been deleted.', 'success');
}
})
});
});

Was simpler than I thought. Use a form_tag and in jQuery use $(this).parents('form'); If you try to grab the form by the id to submit, it won't work. Did not need to use AJAX.
HTML
<%= form_tag(registration_path(current_user), { method: :delete, id: "deleteForm" }) do %>
<button id="delete" type="submit"><i class="fa fa-trash"></i>Delete Account</button>
<% end %>
jQuery
$('#delete').on('click', function (e) {
e.preventDefault();
var form = $(this).parents('form');
swal ({
title: 'Are you sure?',
text: 'You will not be able to recover your account!',
icon: 'warning',
closeModal: false,
allowOutsideClick: false,
closeOnConfirm: false,
closeOnCancel: false,
buttons: [ 'No', 'Yes']
}).then((willDelete) => {
if (willDelete) {
swal("Your account has been deleted!", {
icon: "success",
});
form.submit();
} else {
swal("Your account is safe.");
}
});
});

Related

Hide div after page reloaded on sweet alert

i'm using sweetalert in ajax post data, and have a div element that i want to hide after page reload, from the code below what i can do to do that :
$(document).ready(function() {
$(document).on('click', '#approve', function() {
swal.fire({
title: 'Are you sure ?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.value) {
$('.leftForms').each(function(e) {
valuesToSend = $(this).serialize();
$.ajax($(this).attr('action'), {
url: 'data.php',
type: 'POST',
method: $(this).attr('method'),
data: valuesToSend
})
.done(function(response) {
swal.fire({
title: 'Data berhasil diupdate!',
text: response.message,
icon: 'success'
}).then(function() {
location.reload();
localStorage.removeItem('leftcontent');
localStorage.getItem('rightcontent', data);
});
})
});
}
})
});
});
i want to hide this, at the moment after location.reload(), is that possible ?
<div id="content1">
<p>blaa..blaa.. bla..</p>
</div>
Why are you reloading the page ? You can hide remove the div using JavaScript instead.
Instead of location.reload(); do $("#content1").remove(); to remove the element or $("#content1").hide() to hide it.
Also localStorage.removeItem('leftcontent'); and localStorage.getItem('rightcontent', data); isn't being executed.
if you want this choice to actually persist you need to save something to a database for clear reasons, you could use local storage but it will be cleared if the user clears the cache, just save the choice to the local storage then just check for that var when the page reloads and remove the element with:
...
.then(function() {
localStorage.setItem('choice','hide');
location.reload();
$(document).ready(function() {
if(localStorage.getItem('choice')=='hide'){
$("#content1").remove();
}
...
but as #Gazmend pointed out you don't even need to reload the page, just remove the element instead of reloading if reloading is not necessary for other reasons

SweetAlert2 : Some difficults to configure my alert

I'm trying to use sweetAlert2. https://sweetalert2.github.io/
The plan is as follows:
1) Display of the main alert
2) If he clicks on "Cancel", I close the alert normally.
3) If he clicks on "OK", then the button goes to the loading position, but the alert does not close. And in the meantime I make an Ajax request. And when it's over, only then can I close the 1st alert and view the second.
4) When I click on "OK" on the second alert, the page reloads.
But for the moment I cannot manage well how to display the alerts when I click on OK and Cancel.
I have this code below:
Swal.fire({
title: 'Change to '+planName,
text: message,
icon: "info",
showCancelButton: true,
showLoaderOnConfirm: true,
preConfirm: function () {
// todo - actually change the plan!
$.ajax({
url: changeUrl,
method: 'POST'
}).done(function(){
Swal.fire({
title: 'Plan changed !',
icon: 'success',
},function() {
location.reload();
})
});
}
});
When I click on CANCEL on the 1st alert, everything is going well.
But if I click OK, then I see the confirmation button go into "loader" but the alert closes directly. Then my Ajax request is made and then displays the second alert.
Could anyone help me please ?
EDIT: current code :
Swal.fire({
title: 'Change to '+planName,
text: message,
icon: "info",
showCancelButton: true,
showLoaderOnConfirm: true,
preConfirm: function () {
// todo - actually change the plan!
return $.ajax({
url: changeUrl,
method: 'POST'
}).done(function(){
Swal.fire({
title: 'Plan changed !',
icon: 'success',
},function() {
location.reload();
})
});
}
});
How about doing this
Swal.fire({
title: 'Change to '+planName,
text: message,
icon: "info",
showCancelButton: true,
showLoaderOnConfirm: true,
preConfirm: function () {
// todo - actually change the plan!
return $.ajax({
url: changeUrl,
method: 'POST'
}).done(function(){
Swal.fire({
title: 'Plan changed !',
icon: 'success',
},function() {
location.reload();
})
});
}
});
Here is a sandbox with a similar implementation
https://codesandbox.io/s/muddy-smoke-5gwf0

When I use Ajax sweet Alert doesn't show image. I'm working with laravel

When I use Ajax sweet Alert doesn't show image. I'm working with laravel.
This is my code, if I delete the ajax function or I use a image from another website it works.
I really have no clue, I think laravel need some kind of authetication from a Ajax request. Please help me out!
$(document).ready(function() {
$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this team!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal({
title: "Checking...",
text: "Please wait",
icon: icons,
button: false,
allowOutsideClick: false
});
$.ajax({
url: linkURL,
type: 'GET',
success: function(result){
swal("The team was deleted!");
}
});
} else {
swal("The team was NOT deleted!");
}
});
}
});

Redirect to a different page after a Success Sweet Alert is closed

For some reason, the following code isn't working for me even though it looks very similar to what I've found online. I want a sweet alert to pop up and then when the user clicks the confirm button I want the script to send them back to the homepage. However, this just shows the sweet alert and does not redirect them on close. Also please note Sweet Alert is installed properly. Here's my code:
swal({
title: 'Signed Up!',
html: 'Thank you for registering',
type: 'success',
confirmButtonText: 'Got it!'
}, function () {
window.location.href = "index.php";
});
swal({
title: 'Signed Up!',
html: 'Thank you for registering',
type: 'success',
confirmButtonText: 'Got it!'
}).then(function () {
window.location.href = "index.php";
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'cancel') {
window.location.href = "cancel.php";
}
});
I have not tested this but the documentation says this would work. https://sweetalert2.github.io/

SweetAlert with Java Servlet

I wanted to pause form's onsubmit, so I could ask user to confirm action before proceed.
So here's my form:
<form action="<%= request.getContextPath()%>/Controller"
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>
Then, I created the JavaScript function, using SweetAlert:
function alertInfo(action) {
document.querySelector(action).addEventListener('submit', function (e) {
var form = this;
e.preventDefault();
if (action === "remove_book") {
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function () {
form.submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
});
}
But for some reason, I am unable to prevent page reload on form submit. Am I doing someting wrong?
PS: I already tried with return alertInfo() in form and returning boolean value from JS function with no success.
Why not call the function from the form like this, the the alert will be prompt before submitting the form:
HTML
<form action="<%= request.getContextPath()%>/Controller" method="GET" id="remove_book" onclick="myAlertFunction(event)">
<input type="submit">
</form>
JavaScript
function myAlertFunction(event) {
event.preventDefault()
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function() {
$("#remove_book").submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
And if you want to prevent the reload, you can always use event.preventDefault()
Here is an example: JSFiddel
If you don't want the page reloads you could use an AJAX call. When you use the submit() you will always reload the page because is how submit works.
$.ajax({
method: "POST",
url: YOUR_ACTION_URL,
data: $('form').serialize(),
success: function(data){
//here you could add swal to give feedback to the user
}
});
In your controller you have to define the method as produces JSON, if you are using Spring, the annotation is #ResponseBody

Categories