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');
}
})
});
});
CodePudding user response:
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 ></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.");
}
});
});