AJAX call with error catching in SweetAlert2 - javascript

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/

Related

How do I pass through text inputted in SweetAlert2 box to a .then method?

Right now I am doing the following:
function resetPassword(email) {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Enter the email address',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Send Reset Email',
}).then((input) => {
firebase.auth().sendPasswordResetEmail(email)
.then(() => {
Swal.fire({
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
But it is not working, what am I doing wrong?
My main outcome is to get the email, pass it through to firebase auth api, send the email, then put one more diag box out that says "done" basically. But the input is not coming through. Why is this?
Thanks in advance.
The Swal result will be stored in an object with the same name that you define in the passed parameter to the 'then' function, in this case, input. The email address is stored in input.value. I'd also remove the unnecessary email parameter from the function declaration. This should work:
function resetPassword() {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Enter the email address',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Send Reset Email',
}).then(({value: input}) => {
firebase.auth().sendPasswordResetEmail(input)
.then(() => {
Swal.fire({
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
Thank you for your answer #Chris, but after yours not working I then went onto the SA2 docs and found a login page, then heavily modified it to the following:
function resetPassword() {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Please Enter Your Email Address',
html: `<input type="text" id="email" class="swal2-input" placeholder="mail#website.com">`,
confirmButtonText: 'Sign in',
focusConfirm: false,
preConfirm: () => {
const email = Swal.getPopup().querySelector('#email').value
return { email: email }
}
}).then((result) => {
firebase.auth().sendPasswordResetEmail(result.value.email)
.then(() => {
Swal.fire({
icon: 'success',
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
Thanks for your help though and the solution which I am posting now did take a long time to make so you are still greatly appreciated.
Have a nice day!

reload page after ajax using swal

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()
});

Open swal without clicking any ok or cancel icon

I am using sweetalert 2 where I just need to open the swal directly calling ajax instead of doing an confirm or something, what change I need to do, following this code
https://sweetalert2.github.io/recipe-gallery/bootstrap.html
Tried it like this
$(document).on('click','.readmore',function() {
swal({
title: 'ajax request pending',
text: 'processing request',
showConfirmButton: false,
closeOnConfirm: false,
preConfirm => function(){
url: 'https://example.com/controller/method/action',
type: post,
dataType: json,
data: { key: value },
success: swal.confirm( response.message ),
error: swal.confirm( response.message )
}
},
function(){
swal({
title: 'ajax request finished',
text: response.message,
showSpinner: false,
showConfirmButton: true,
closeOnConfirm: true
});
}
});
But it ended up in a error :d
Uncaught SyntaxError: missing : after property id

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

How to show loading function before get data from server?

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>

Categories