Uncaught (in promise) cancel using SweetAlert2 - javascript

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

Related

How can I pass RESULT from javascript to laravel function as amount?

I want to save this result as amount, when I do console.log(result); I see that know what number I put in input, but how to save it in Laravel function?
function makeOffer(nftid) {
swal({
title: "Do you want to make offer?",
text: "Enter amount",
input: 'text',
type: 'warning',
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
}).then((result) => {
if (result) {
axios.post("/myaccount/makeoffer/" + nftid).then(response => {
window.location.reload();
});
}
});
}
public function makeOffer($id, Request $request){
$nft=NFT::where('id','=',$id)->first();
if($nft->status=='pending') {
$nft_auction = new NftAuctions();
$nft_auction->nft_id = $nft->id;
$nft_auction->owner_id = $nft->user->id;
$nft_auction->buyer_id = Auth::id();
$nft_auction->amount = "there should be amount";
$nft_auction->status = 'pending';
$nft_auction->save();
return back();
}
else{
abort(404);
}
}
Axios' .post() method takes 2 arguments; the URL and the data you want to send to the backend, so adjust it to:
axios.post("/myaccount/makeoffer/" + nftid, {'amount': result})
.then(response => {
window.location.reload();
});
Then, in your backend, you can access this as $request->input('amount'):
public function makeOffer($id, Request $request){
$nft = NFT::find($id);
if($nft->status == 'pending') {
$nftAuction = new NftAuctions();
// ...
$nftAuction->amount = $request->input('amount');
// ...
$nftAuction->save();
return back();
}
}
Some notes:
Model::where('id', '=', $id)->first() can be shortened to Model::find($id).
Model names are PascalCase and singular: NFT should be Nft, and NftAuctions should be NftAuction
Documentation:
Axios .post() method
Laravel: Retrieving Input

Wait for Sweet Alert input if a condition is met, otherwise continue

I have this script, which in some cases may require user input. It works, but the script continues regardless of the result of the Sweet Alert input.
$('#cart').on('click', '.button', function() {
var code = $(this).data('code')
if ((code !== '') && (code !== null) && (code !== undefined)) {
var repeated = 0
var secondary = null
if (code.startsWith('ABC')) {
swalBs.fire({
text: 'Enter secondary code',
showCancelButton: true,
cancelButtonText: 'Cancel',
showConfirmButton: true,
confirmButtonText: 'Confirm',
reverseButtons: true,
input: 'text',
inputValidator: (value) => {
if (!value) {
return 'Code required'
}
}
})
.then((result) => {
console.log(result)
secondary = result.value
})
}
if (repeated < 1) {
$.post(serviceUrl, {
c : code,
s : secondary
}, function(response) {
...
})
.fail(function() {
...
})
} else {
swalBs.fire('Error', 'Code already entered', 'error')
}
} else {
swalBs.fire('Enter code', 'Field must not be blank.')
}
})
How can I make this script wait for the Sweet Alert input while still allowing the $.post to happen when the if (code.startsWith('ABC')) condition is not met (and Sweet Alert is not needed)?

Highlighting default text input in sweetAlert

I have a SweetAlert2 that allows text input, and I give it a default value. I'd like this default value to be highlighted when the alert pops up, so that the user can immediately overwrite it if needed. Here's an example:
And here is the function that I call with the sweetAlert options:
window.sweetPrompt = function (title, message, callback, input, keepopen, allowOutsideClick, allowEscapeKey) {
sweetAlert({
title: title,
text: message,
input: 'text',
confirmButtonColor: "#428bca",
preConfirm: function(text) {
return new Promise(function(resolve) {
if (!keepopen) {
resolve();
} else {
callback(text);
}
});
},
inputValidator: function(text) {
return new Promise(function (resolve, reject) {
if (text) {
resolve();
} else {
reject('Cannot be empty!');
}
});
},
inputValue: input,
showCancelButton: true,
reverseButtons: true,
allowOutsideClick: allowOutsideClick,
allowEscapeKey: allowEscapeKey
}).then(callback, function(dismiss){});
};
How would I go about doing this (if it's possible) ? I thought about using jQuery but I'm not sure how to get the reference to the sweetAlert dialogue.
Any suggestions would be appreciated.
Here you go:
Swal.fire({
input: 'text',
inputValue: 'input value',
didOpen: () => {
Swal.getInput().select()
}
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#11"></script>
PS. Please note that SweetAlert2 and SweetAlert are two different projects with slight differences in API.
SweetAlert2 documentation: https://sweetalert2.github.io/

Asp.Net MVC Javascript functions not working in Razor if statement

I'm returning View from my action after post event and doing some javascript things in view. But javascript function calls not working in razor if statement.
$.post("#Url.Action("Login", "Account")",
accountObject,
function(result) {
$.unblockUI();
if (result.isSuccess) {
var object = #Html.Raw(Json.Encode(#Model.CrmIntegrationModel));
$.post("#Url.Action("File")",
object,
function(resultData) {
#if (!Model.IsFileViewModelEmpty)
{
var model = Model.UploadFileViewModel.PortalEntity as Task;
if (!Model.UploadFileViewModel.HasError)
{
#:alert("Worked! ");
if (model != null)
{
var task = model;
if (task.State != State.Open)
{
<text>
$.blockUI({ target: '#uploadPanel', message: null });
$(swal({
title: "Warning",
text:
"File can not be uploaded for task that status is not open.",
type: "warning",
confirmButtonClass: "btn-warning",
confirmButtonText: "OK"
}));
</text>
}
else
{
#: LoadDocumentTypes();
}
}
else
{
#: LoadDocumentTypes();
}
}
else
{
<text>
$.blockUI({ message: null });
$(swal({
title: "Warning",
text: '#Html.Raw(Model.UploadFileViewModel.ErrorMessage)',
type: "warning",
allowOutsideClick: false,
showConfirmButton: false
}));
</text>
}
}
});
}
});
When I passif (!Model.UploadFileViewModel.HasError) statement as true my #:alert("Worked !"); not working. Also below lines #: LoadDocumentTypes(); function call not working. How can I resolve this problem ?

SweetAlert2 Update Counter for User Feedback

Is there a way to update the text on SweetAlert2 alert to show the number of rows that have been processed in a a really long javascript loop? Unfortunately people have been leaving the page and then only half the rows get saved.
I thought I might be able to use jQuery type syntax, but not sure what the proper select might be.
$('#rowsprocessed').text(count);
swal({
title: 'Save Order.',
input: 'checkbox',
inputValue: 0,
inputPlaceholder: 'Remove Zero(s) Quantity Item(s) Before Saving the Order?',
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.',
type: 'info',
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
preConfirm: function(checkbox) {
return new Promise(function(resolve, reject) {
removeZeros = checkbox;
setTimeout(function() {
swal.showLoading();
$.post("/components/com_sails/views/neworderform/saveOrderHeader.php",
{
orderid: orderid,
accountid: accountid,
buyerid: buyerid,
vendorid: vendorid,
ponumber: ponumber,
specialinstr: specialinstr,
orderDate: orderDate,
shipDate: shipDate,
cancelDate: cancelDate
},
function (result) {
if (result.return == 1) {
// assign order id to holder field
$('#orderInput').jqxInput('val', result.ordernbr);
// loop through our rows and save depending on the removeZero marker
var rows = $('#jqxgrid').jqxGrid('getdisplayrows');
var rowsToRemove = [];
var linessaved = 0;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// get row info for delete
if ((removeZeros == 1) && row['quantity'] == 0) {
rowsToRemove.push(row.uid);
}
// run database update
$.ajax({
type: 'POST',
url: '/components/com_sails/views/neworderform/saveOrderLine.php',
data: {
orderid: result.ordernbr,
removezeros: removeZeros,
rowdata: row
},
success: function (rowSaveData) {
// alert('rowSaveData ' + rowSaveData.return + " " + rowSaveData.isbn + " " + rowSaveData.action + " " + rowSaveData.msg + " row.uid: " + row.uid);
// if there is a problem what do we do????
if (rowSaveData.return == 1) {
$('#rowsprocessed').text(i);
}
if (rowSaveData.return == -1) {
// add to error message?
}
},
datatype: 'json',
async: false});
}
if (removeZeros == 1) {
// delete our zero rows
var commit = $("#jqxgrid").jqxGrid('deleterow', rowsToRemove);
$('#jqxgrid').jqxGrid('render');
lastselectedrow = -1;
}
// set save marker??
isDirty = false;
}
else {
// there was an error saving the header
// need to get this logged
alert('Error Saving Order. Details: ' + result.msg);
}
}, "json");
resolve();
}, 2000);
});
},
allowOutsideClick: false
}).then(function() {
swal({
type: 'success',
title: 'Order saved',
html: '<b><div id="rowsprocessed">0</div></b> rows saved.',
timer: 4000
});
})
Absolutely you can, you just pass in an additional element with your {html: "..."} that you can use as a means of updating the user.
Something Like:
{
...
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.<br/><span class="swal2- status"></span>',
...
}
And then use this syntax to update:
var $status = $('.swal2-status');
$status.html("I'm an update");
See the example here:
https://jsfiddle.net/1mvnxp3L/

Categories

Resources