How do I show one swal at the time in javascript - javascript

I created a swal for a notification. To show up in the screen the result of the ajax function has to be 0. But this ajax function run every 2 seconds. Sometimes the ajax function returns more than one result has 0, so the swal dont stop showing, just showing the other when the user click in the close button. I would like to show one swal at the time, but setInterval function isnt alowing me to do it.
This is the funtion with the swal:
function montarModalLigacao(cdRamalLigacao = null)
{
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {cdLigacaoRamal: cdRamalLigacao});
console.log(dsHtml);
if (dsHtml)
{
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText:'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
});
}
}
And here is where i call it, with the setInterval:
$(document).ready(function(){
setInterval(function(){
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}

Do not do it on an interval, call it when you are ready for the next one to happen.
function montarModalLigacao(cdRamalLigacao = null) {
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {
cdLigacaoRamal: cdRamalLigacao
});
console.log(dsHtml);
if (dsHtml) {
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText: 'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
setUpCall();
});
} else {
setUpCall();
}
}
function setUpCall() {
setTimeout(function() {
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}
$(document).ready(setUpCall);

Related

Cancel function execution with SweetAlert

I have buttons to execute scripts in my Sheets Addon
<button class="button-68" role="button" onclick="morphf3994()">Unir columnas con el mismo encabezado</button>
<script>
function morphf3994() {
swaload()
google.script.run
.withSuccessHandler(swalsuccess)
.withFailureHandler(swalerror)
.merge_Columns();
}
</script>
And SweetAlert shows a Executing... alert while the script is making its function.
<script>
function swaload() {
Swal.fire({
titleText: "Ejecutando...",
text: 'Por favor, no toques ni cierres el documento.',
icon: 'warning',
allowOutsideClick: false,
preConfirm: Swal.showLoading(),
showLoaderOnConfirm: true,
showConfirmButton: false,
showCancelButton: true,
})
}
</script>
The Alert has just a Cancel button, but I don't know how to implement the CancelButton to stop the button function before finishing (in this case the .merge_Columns() function. Right now the Cancel Button just close the loading window.
Thanks!
Use then function of swal in your code. Reference
<script>
function swaload() {
Swal.fire({
titleText: "Ejecutando...",
text: 'Por favor, no toques ni cierres el documento.',
icon: 'warning',
allowOutsideClick: false,
preConfirm: Swal.showLoading(),
showLoaderOnConfirm: true,
showConfirmButton: false,
showCancelButton: true,
}).then((result) => {
if (result.isConfirmed) {
return true;
} else if (result.isDenied) {
return false;
}
})
}
</script>
apply condition in morphf3994 function
<script>
function morphf3994() {
if(swaload()){
google.script.run
.withSuccessHandler(swalsuccess)
.withFailureHandler(swalerror)
.merge_Columns();
}
}
</script>
Well, with this edit the function is running, but what i need is the code to STOP the .merge_Columns from executing. The function is already running when the Cancel button appears but I don't know the apps script code to stop the function.
<script>
function morphf9566() {
if(swaload()){
}
else {
google.script.run
.withSuccessHandler(swalsuccess2)
.withFailureHandler(swalerror)
.merge_Columns();
}
}
</script>
Thanks

Sweet alert not returning true or false?

Sweet-alert not returning the true or false after calling this get_alert() function please suggest some suggestions how could we able to work this
function get_alert() {
$('#removeactive').on('click', function(e) {
e.preventDefault();
var message = $(this).data('confirm');
//pop up
swal({
title: "Are you sure ??",
text: message,
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(isConfirm) {
console.log(isConfirm == true);
if (isConfirm == true) {
return true;
} else {
return false;
}
});
});
}
<button id="removeactive" data-confirm="Are you sure?" type="button">Click</button>
You should not need a function to assign an event handler. Also you have not told us when you call get_alert. Calling get_alert will NOT show the alert, only assign the handler
Here I run on load of the page
If the removeactive element is dynamic, you need to change to
$(document).on('click','#removeactive', function(e) {
or better:
$(document).on('click','.removeactive', function(e) {
so any element with that class can call the alert
You also need to remove active where you know the status of the isConfirm
Here is a working example
$(function() { // on page load
$('#removeactive').on('click', function(e) {
e.preventDefault();
var message = $(this).data('confirm');
//pop up
swal({
title: "Are you sure ??",
text: message,
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(isConfirm) {
console.log("confirmed?", isConfirm);
if (isConfirm) console.log("deleting"); // here you delete
else console.log("cancelled"); // here you do whatever or nothing
// You cannot return anything
});
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<button id="removeactive" data-confirm="This will remove the active widget from the sprocket" type="button">Click</button>

Delay appearance of buttons in sweetalert2

I am using SweetAlert2 to communicate some feedback to the user. This is a learning app, so, I want the feedback to persist for some time. I do not want to show any buttons immediately after the feedback is displayed because people have a tendency to just click on 'OK' or 'Cancel', without reading the text.
The number of characters in the feedback varies from screen to screen, so, I am using the timer parameter of sweetalert2 to be some multiple of the number of characters in the text. But, the timer feature is imperfect because people have different reading speeds. Ideally, I would want the 'OK' button to appear after the timer has timed out. Is there some sort of an API call I can make to dynamically change the property of the alert box?
swal({
html: feedback,
timer: feedback.length*50,
showCloseButton: false,
showCancelButton: false,
showConfirmButton: false,
allowOutsideClick: false,
});
I don't see any method to hide and show the buttons, but you can disable and enable them:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
swal.disableButtons();
setTimeout(swal.enableButtons, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
or make them transparent:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
var b = swal.getConfirmButton()
b.style.opacity = 0
b.disabled = true
setTimeout(function() {
b.disabled = false
b.style.opacity = 1
}, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
or hide and show:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
var b = swal.getConfirmButton()
b.hidden = true
b.disabled = true
setTimeout(function() {
b.disabled = false
b.hidden = false
}, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
Hi to achive this you can use a set timeout function and call jQuery's .show() function on the buttons that you wish to show (Assuming you are ok with using jQuery).
The following code should help you out
swal({
html: feedback,
timer: feedback.length*50,
showCloseButton: false,
showCancelButton: false,
showConfirmButton: false,
allowOutsideClick: false,
});
setTimeout(function () {
$(".swal2-cancel").show();
$(".swal2-confirm").show();
$(".swal2-close").show();
}, 3000);
Hope this helps :-)

Timer with confirm and cancel button

i'm a noobs at sweet alert.
Is it possible to create a sweet alert prompt which has confirm button, cancel and timer.
The logic is if the alert not confirmed, timer automatically execute the same function with cancel. I have tried and stuck. even if the alert confirmed, the timer still counting and the the cancel function is called.
sweetAlert({
title: 'Stay in fullscreen',
text: "You will be logged out in 10 seconds or if you leave the fullscreen!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#ff0000',
confirmButtonText: 'Go fullscreen!',
cancelButtonText: 'Leave this page!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-warning',
closeOnConfirm: 'true',
timer:'10000',
buttonsStyling: false
},function(isConfirm) {
if (isConfirm) {
return launchIntoFullscreen(document.documentElement) // timer still still counting
} else {
return Redirect()
}
}).then(function () {
swal(
window.alert('teest')
)
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'timer') {
return Redirect()
}
})
Checking the isConfirm argument for null should tell you if the callback was initialized by the timer finishing.
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
As far as I could find, this behavior is not documented, but I believe this is the relevant bit of the source
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
the code above still execute cancelFunction();
i add a line before Confirmfunction.
if (isConfirm !=null && isConfirm != false) {
closeInSeconds = Number.MAX_VALUE/1000; // this line extends timer time
document.documentElement);
}
else {
Redirect();
}

Uncaught (in promise) cancel using SweetAlert2

how do I properly escape the cancel button without throwing an error when using promises? My code throws an alert confirmation with a required checkbox. the code executes as it should to the user, but it throws an error in the console window:
Uncaught (in promise) cancel
//validation logic all passes...Now proceed to...
else
{
//determine and parse Discounts
var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
.done(function(json_data){
var theResponse1 = $.parseJSON(json_data);
myDiscountRate = theResponse1['ourDiscountFound'];
}).then( function(callback){
priceRate = priceRate * (1 - (.01 * myDiscountRate));
newRate = priceRate.toFixed(2);
}
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to Your new Rate is :'+newRate,
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
$.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
resolve();
} else {
reject('You must agree to our Terms & Conditions ');
}
});
},
allowOutsideClick: false
}).then(function(json_data) {
})
});
Update (Jan 2017): This issue has been fixed in v7: v7 upgrade guide ↗
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
PS. the package you're using is called SweetAlert2, not SweetAlert. In future questions please mention it so you can get more relevant answers.
SweetAlert2 rejects the result promise when the cancel button is pressed. You can handle that:
swal({
…
}).then(function(json_data) {
…
}, function(dismiss) {
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
If you don't need to do anything with the json_data, you might also use the catch method.
new Promise(function(resolve, reject) { is not necessary. $.post() returns a jQuery promise object.
Possible solution substitutes Promise.reject() for new Promise() constructor; removed .then() that was placed as an option to first swal() call; pattern appears to expect a Promise to be returned from preConfirm, though not certain what value is expected to be returned from .done() other than json_data.
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to ',
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
if (result) {
return $.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
} else {
return Promise.reject('You must agree to our Terms & Conditions ');
}
},
allowOutsideClick: false
});
you will need to catch the action for cancel
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function(json_data) {
//delete item
}, function(dismiss) {
if (dismiss === 'cancel' || dismiss === 'close') {
// ignore
}
})
Adding catch(swal.noop); at the end swal function will solve this problem
For example:
swal({
}).then(function() {
}).catch(swal.noop);

Categories

Resources