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>
Related
Currently this function emails the person who inputs their email in the text field and the sender is our API ecommerce email. The To: is the person who made the request.
My trouble is I can't seem to add possibly a CC: field to also add so we know who made the request.
Below is the function, there's more to it that I can provide if needed.
$('#emailCart').click(function(e) {
e.preventDefault();
Swal.fire({
title: 'Enter Email',
input: 'text',
showCancelButton: true,
confirmButtonText: 'Email Cart',
preConfirm: (email) => {
if (email.length === 0 || !emailIsValid(email)) {
Swal.showValidationMessage('Please enter a valid email address.');
}
}
}).then((result) => {
if (result.value) {
$.ajax({
url: apiUrl + '/cart/email',
method: 'post',
headers: {
'X-CSRF-TOKEN': csrfToken
},
data: {
email: result.value
},
success: function() {
Swal.fire({
type: 'success',
title: 'Success',
text: 'Your cart has been emailed.',
timer: 1500
});
},
error: function() {
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Cart could not be emailed.'
})
}
});
}
});
});
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()
});
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
I have this function in my controller:
[HttpPost]
public IActionResult DeleteBooking(string bookingId)
{
Console.WriteLine("id: " + bookingId);
DeleteResult<IBooking> deleteResult = bookingDomain.DeleteBooking(Guid.Parse(bookingId));
return View("Index");
}
And in my View I need to delete a booking using a button. So I made a javascript onclick function. It goes to the function in my controller but it passes null as parameter instead of the id as string idk what to do anymore...
function deleteBooking(bookingId) {
console.log(bookingId); // this works
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url: '/Booking/DeleteBooking/', // the URL of the controller action method
data: bookingId, // optional data
success: function (result) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
},
error: function (req, status, error) {
Swal.fire(
'Error!',
'Your file could NOT be deleted.',
'error'
)
}
});
}
})
}
The console.log(bookingID) shows me the right id but in the controller function I just get null.
Try updating the data portion of your ajax call to look like this:
$.ajax({
type: 'POST',
url: '/Booking/DeleteBooking/', // the URL of the controller action method
data: { bookingId: bookingId } , // optional data
success: function (result) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
},
error: function (req, status, error) {
Swal.fire(
'Error!',
'Your file could NOT be deleted.',
'error'
)
}
});
When passing data to controller via Ajax, the data must be sent as key value pairs as follows:
data: { "bookingId": bookingId }
Key must be same as the parameter name in the controller.
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/