I have some swal code like this:
$('#config-reset').click(function(event) {
event.preventDefault()
swal({
text: 'some text',
dangerMode: true,
showLoaderOnConfirm: true,
buttons: true,
})
.then((result) => {
if (result !== null) {
return $.post("url")
}
return false
})
.then((result) => {
if (result.result.success == 'done') {
swal({ text: "Done", icon: "success", });
}
else{
swal(result.result.error);
}
})
.catch(err => {
swal(err.statusText);
});
})
})
After the ajax call returns and Done/success swal is cleared I want to reload the page. If I put the reload after the swal it happens before the swal is cleared. Same if I put it in a .then after the second .then. How can I get the reload to not run until after the alert is cleared?
Please add option onClose.
swal({
text: "Done",
icon: "success",
onClose: function(){
location.reload()
}
});
If you use sweetalert v1, please try like this:
swal({
text: "Done",
icon: "success"
confirmButtonText: "Ok",
},
function(isConfirm){
if(isConfirm)location.reload()
});
Or:
swal({
text: "Done",
icon: "success"
}).then((value)=>{
if(value)location.reload()
});
Related
$(document).ready(function () {
$('form').submit(function(){
isSubmitting = true
})
$('form').data('initial-state', $('form').serialize());
$(window).on('beforeunload', function() {
return Swal.fire({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
Swal.fire("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
Swal.fire("Your imaginary file is safe!");
}
});
// return 'You have unsaved changes which will not be saved.'
}
);
});
I'm using above code to show alert on page refreshing.
How to show a customization styling alert box instead of default in react or is there any other way to show popup
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 use Ajax and SweetAlert2 library to use alert UI. I search the how can I show the loading process during get data from server and I thought I can use beforeSend function. I write code like this.
So I put the Loading Process code inside the beforeSend but I don't know why It's not working. So I want to check is it works in beforeSend code so I write console.log code inside it and it actually works. But I don't know why the Swal.showLoading(); code is not working.
When I just type it in google console it works.
Loading Code is Simple.
Swal.showLoading();
And I want When it finish it show Finish Code.
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
// contentType: "application/json",
url: `/${userId}/admin/getData`,
dataType: "json",
beforeSend: function () {
Swal.showLoading();
console.log('Loading');
},
success: function (redrawData) {
console.log(JSON.stringify(redrawData));
let existTable = $('#dataTable').DataTable();
existTable.destroy();
$('#dataTable').DataTable({
aaData: redrawData, // Returned Data from Server
aoColumns: [{
mData: 'id',
"render": function (value, type, row) {
return `${row.id}`;
}
},
{
mData: 'name'
},
{
mData: 'type'
},
{
mData: 'url'
},
{
mData: 'imgurl',
"render": function (value, type, row) {
return `<img src="${row.imgurl}">`;
}
},
{
mData: 'sumlang'
},
{
mData: 'pjdate1'
},
{
mData: 'pjdate2'
},
{
mData: 'githuburl'
}
]
})
},
complete: function () {
Swal.fire(
'Get!',
'Your file has been deleted.',
'success'
)
},
error: function (e) {
Swal.fire(
'Failed to save',
'If this message is output continuously, please contact to administrator.',
'error'
)
}
});
}
})
}
I never used SweetAlert but I have taken a look on their website exmaple and found this
const ipAPI = 'https://api.ipify.org?format=json'
Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
showLoaderOnConfirm: true,
preConfirm: () => {
return fetch(ipAPI)
.then(response => response.json())
.then(data => Swal.insertQueueStep(data.ip))
.catch(() => {
Swal.insertQueueStep({
type: 'error',
title: 'Unable to get your public IP'
})
})
}
}])
They use fetch with preConfirm in their exmaple, but in your case, I guess you can try to use preConfirm attribute that return the Promise created by the JQuery $.ajax() function
Example:
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!',
showLoaderOnConfirm: true,
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: function(){
return $.ajax(...); //Your ajax function here
}
});
}
You could just set the showLoaderOnConfirm to true to show the preloader when you click the continue button. Then, add the ajax call inside the preConfirm. Just make sure to return the response and catch any errors.
Swal.fire({
title: 'Submit your Github username',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Look up',
showLoaderOnConfirm: true,
preConfirm: (login) => {
return fetch(`//api.github.com/users/${login}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
Swal.showValidationMessage(
`Request failed: ${error}`
)
})
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.value) {
Swal.fire({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
I'm scratching my head for a couple of days now and I can't get SweetAlert2 to do a AJAX call and return "Success" if it succeeded or show me an error in the same box if something goes wrong, leaving the user free to try again.
My implementation is following so far. The problem is that it shows the error in the box, but closes it at the same time:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve,reject) {
$.ajax({
url: '*****', // Invalid URL on purpose
type: 'POST',
data: {test: true}
})
.done(function(data) {
resolve(data)
})
.fail(function() {
reject()
});
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
title: `Success`,
text: result.value
})
}
}).catch((result) => {
swal.showValidationError('POST failed. Please try again.');
})
In the documentation I cannot find a AJAX call with a showValidationError. The closest I found is a fetch() call, but those are only for GET, as far as I know.
I also tried something like: return true, return false, throw new Error, promises inside promises, but that was all trial-and-error, so I came here.
I also made a fiddle: https://jsfiddle.net/xpvt214o/306267/
Thanks in advance for any help and/or suggestions.
After one more day I figured it out. I had to .then and .catch the $.ajax and attach swal.showValidationError on it in order to work.
On a AJAX error it will show following in the same box now (The user can try as many times as he pleases):
On success following:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: () => {
return $.ajax({
url: '***',
type: 'POST',
data: 'test'
})
.then(response => {
return response
})
.catch(error => {
//console.log(error); // Nice to view which properties 'error' has
swal.showValidationError(
`An error ocurred: ${error.status}`
)
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
type: 'success',
title: 'Success',
text: result.value
})
}
})
Fiddle: https://jsfiddle.net/z3kfhsj8/6/
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!");
}
});
}
});