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
Related
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.");
}
});
});
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
I'm using JQueryFullCaledar and have written a function to hijack the eventclick. By default it just ran this code:
var id = event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
//alert("Event Removed");
}
})
I've hijacked this event to instead open a context menu offering three options:
Edit, Delete Close Menu. If they choose delete it runs the same function as before but with an if statement (aided by sweet alerts) to check they're sure.
If they choose close, it just closes the menu
If they choose edit it sends the Id of the appointment over to a PHP file via AJAX so I can update it. I've noticed when updating a bunch of them the appointment isn't correct after the first couple of opens. So, I added a catch to alert the ID of the appointment before runnning AJAX.When I open my first appointment, I get an alert with the first appointment ID. I close that, then open another, at which point I first get an alert with the first ID, then a second with the new ID, then opening another appointment gives me those two alerts and a third with the third appointments ID and so on... I've tried setting the ID to blank on clicking cancel or save on the edit file but no luck.
Here's the whole code for the event click function:
eventClick:function(event)
{
$('.appt_menu').removeClass('hidden').css( {position:"absolute", top:event.pageY, left: event.pageX});
$('a.close_menu').on("click",function(){
$('.appt_menu').addClass('hidden');
})
$('a.edit_appt').on("click",function(){
$('.appt_menu').addClass('hidden');
//show me the ID before sending it via AJAX
alert(event.id);
$('#modalwindow').load("Form_Edit_Appt.php", {id: event.id}, function(data) { calendar.fullCalendar('refetchEvents');});
$('.backdropper, #modalwindow').addClass('show');
}); //end of edit appt function
$('a.delete_appt').on("click",function(){
$('.appt_menu').addClass('hidden');
swal({
title: "Are you sure you want to delete this Appointment?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: ["Not that one!", "Yep, delete it!"],
//buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Your Appointment has been deleted!", {
icon: "success",
});
var id = event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
//alert("Event Removed");
}
})
} else {
swal("Your Appointment has not been removed!");
}
});
})
},
You are binding event handlers every time you do your initial eventClick. Try unbinding with off() every time you set the click handlers so any previously set handlers are removed.
Example:
$('a.edit_appt').off().click(function() {
//your code
});
You're attaching an event handler to the edit_appt on each click of the calendar. When you attach a handler the previous one isn't removed, it stacks up. You should attach it only once (or remove the previous handler before attaching a new one). You could store the event id to a variable and use that in the click handler.
var eventId;
eventClick: function(event) {
$('.appt_menu').removeClass('hidden').css({
position: "absolute",
top: event.pageY,
left: event.pageX
});
eventId = event.id;
}
$('a.close_menu').on("click", function() {
$('.appt_menu').addClass('hidden');
});
$('a.edit_appt').on("click", function() {
if (!eventId)
return;
$('.appt_menu').addClass('hidden');
//show me the ID before sending it via AJAX
alert(eventId);
$('#modalwindow').load("Form_Edit_Appt.php", {
id: eventId
}, function(data) {
calendar.fullCalendar('refetchEvents');
});
$('.backdropper, #modalwindow').addClass('show');
}); //end of edit appt function
$('a.delete_appt').on("click", function() {
if (!eventId)
return;
$('.appt_menu').addClass('hidden');
swal({
title: "Are you sure you want to delete this Appointment?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: ["Not that one!", "Yep, delete it!"],
//buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Your Appointment has been deleted!", {
icon: "success",
});
var id = eventId;
$.ajax({
url: "delete.php",
type: "POST",
data: {
id: id
},
success: function() {
calendar.fullCalendar('refetchEvents');
//alert("Event Removed");
}
})
} else {
swal("Your Appointment has not been removed!");
}
});
});
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!");
}
});
}
});
A controller returns an ActionResult, i.e.:
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// do something
return RedirectToAction("Index", "Orders", null });
}
this works fine is I use an ActionLink in the view.
But the actual call is done via Ajax:
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
with the:
$("html").html(response);
line I'm trying to follow the returned html page.
It doesn't work: the html is rendered wrong (layout and colors are different) and even the address is not correct (of course it remains on the current page, instead to follow the Controller path).
I'm not sure if this is possible to do in jQuery.
Why I use an Ajax call instead of the ActionLink? Because I need to wait a confirm by the user:
$("#btnCancel").click(function () {
event.preventDefault();
swal({
title: "#Resources.MsgCancelOrderTitle",
text: "#Resources.MsgCancelOrderText",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "#Resources.MsgCancelOrderConfirm",
cancelButtonText: "#Resources.MsgCancelOrderCancel",
closeOnConfirm: false,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "#Resources.MsgCancelOrderSuccessTitle",
text: "#Resources.MsgCancelOrderSuccessText",
type: "success"
},
function () {
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
});
}
});
});
If you want to redirect to another view, then don't bother with ajax, it defeats the entire purpose of it. Generally an ajax call returns either some data (JSON or XML) or a small snippet of HTML which is designed to fit somewhere within the page which made the ajax call (generally implemented in MVC as a Partial View).
If you need the redirect, then do it like this:
Once the user confirms their choice via the alert box, then if the request needed uses the GET method (like your example) then simply a call to window.location.href with the appropriate URL will do it. If it was using POST, then normally there'd be a HTML form you could instruct to submit itself.