简体   繁体   English

SweetAlert2和诺言

[英]SweetAlert2 and promises

I'm trying to use SweetAlert2 but I'm having issues to display error messages when something goes wrong. 我正在尝试使用SweetAlert2,但是出现问题时无法显示错误消息。 Also, when the user presses the "Cancel" button, the console displays the error: Uncaught (in promise) cancel. 另外,当用户按下“取消”按钮时,控制台将显示错误:未捕获(承诺)取消。

In short, there is a button on my website. 简而言之,我的网站上有一个按钮。 If the user presses that button a confirm dialog appears (using SweetAlert2). 如果用户按下该按钮,将显示一个确认对话框(使用SweetAlert2)。 Here is my code: 这是我的代码:

swal({
    title: "Are you sure?",
    text: "You will not be able to undo this action!",
    type: "warning",
    showCancelButton: true,
    cancelButtonText: 'No, cancel!',
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, do it!",
    allowOutsideClick: false
    preConfirm: function () {
        return axios.put('/api/endpoint')
        .then(response => {
            console.log('success')
        })
        .catch(error => {
            console.log('failure')
            swal({
                title: "Something went wrong",
                type: "error",
            })
        });
    }
}).then(function (result) {
    if (result.value) {
        swal('Deleted!', 'Your file has been deleted.', 'success')
    } else if (result.dismiss === 'cancel') {
        swal('Cancelled', 'Your file is safe :)', 'error')
    }
});

If something goes wrong, will be nice to display another SweetAlert2 dialog saying "Something went wrong", but instead of that, it looks like SweetAlert2 is somehow capturing the error and displaying it inside the same confirmation box. 如果出了问题,最好显示另一个SweetAlert2对话框,说“出了点问题”,但相反,它看起来像SweetAlert2捕获了错误并将其显示在同一确认框中。 Also, there is the issue with the cancel button: If the user cancels, the console displays the already mentioned error. 此外,取消按钮也存在问题:如果用户取消,控制台将显示已经提到的错误。

SweetAlert2 uses promises and I'm still learning how to use them properly, so maybe there is something that I'm doing in the wrong way. SweetAlert2使用了承诺,并且我仍在学习如何正确使用它们,所以也许有些事情我做错了。

Any help, please? 有什么帮助吗?

Thanks in advance 提前致谢

I just finished messing around with promises inside SWAL2 for the first time, and have made some serious headway into improving part of the UX of my web application because of it. 我刚刚完成了第一次在SWAL2内部兑现承诺的工作,因此,在改善我的Web应用程序的UX部分方面取得了重大进展。 I have used SWAL2 modals a lot, and found that promises work best when getting user input inside a SWAL modal, and validating that input. 我已经使用了很多SWAL2模态,发现在SWAL模态中获取用户输入并验证该输入时,promise最有效。

I am using JQuery 3.2.1 and PHP version 5.6 我正在使用JQuery 3.2.1和PHP 5.6版

This is the first method for trying to do what I am doing, so please don't assume that it will be an exact fit for your project. 这是尝试做我正在做的事情的第一种方法,因此请不要以为它完全适合您的项目。 I am still doing a bit of testing so keep that in mind. 我仍在进行一些测试,因此请记住这一点。

My overall goal was to get users to input the rest of the information I need from them after they log in to their profile for the first time (and/or they have empty fields for necessary database values). 我的总体目标是让用户在他们首次登录个人资料后(和/或他们有必要的数据库值的空白字段)输入我需要的其余信息。

Here is the basis of what I am using Promises and Ajax to do on a macro level: 这是我在宏级别使用Promises和Ajax进行操作的基础:

swal({...}).then(function(result){ //introduction modal

    swal({...}).then(function(result){ //start getting required info

        swal({...}).then(function(result){ //get some more required info

        }, function (dismiss) {}).catch(swal.noop);

    }, function (dismiss) {}).catch(swal.noop);

}, function (dismiss) {}).catch(swal.noop);

Each one of these modals has different inputs that I need, and that I need to validate, with the exception of the first one. 除了第一个模态外,这些模态中的每个模态都有我需要且需要验证的不同输入。

swal({
    html:'Welcome to my web app!',
    imageUrl: '../path-to-image.png',
    imageWidth: 350,
    imageAlt: 'My Logo',
    animation: false,
    showCancelButton: false,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Complete My Profile',
    cancelButtonText: 'Cancel',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-danger',
    buttonsStyling: false,
    focusConfirm: false
    }).then(function(result) {

After my "Welcome to XYZ web app" greeting, I start immediately on my next modal. 在“欢迎使用XYZ Web应用程序”问候语之后,我立即开始下一个模式。 this is super simple. 这非常简单。 Either bring up the next modal if the user hits the one green button they can hit, or display another modal if they close by clicking off it. 如果用户点击了他们可以点击的一个绿色按钮,则调出下一个模态;如果用户通过单击关闭它,则显示另一个模态。 My code continues: 我的代码继续:

swal({
    title: 'Your Basic Information',
    html:
    '<div class="form-group"><input type="text" class="form-control" id="FName" name="FName" placeholder="Last Name"></div>'+
    '<div class="form-group"><input type="text" class="phone_us form-control" maxlength="14" data-mask="(000) 000-0000" id="userPhone" name="userPhone" placeholder="Phone Number"></div>'+
    '<div class="form-group"><div class="input-group"><span class="input-group-addon">$</span><input type="text" class="money form-control" id="avgPrice" name="avgPrice" data-mask="#,##0.00" data-mask-reverse="true" maxlength="5" placeholder="Average Price of your Advice"/></div></div>'+
    '<div class="form-group"><textarea class="form-control" name="FInfo" id="FInfo" rows="6" placeholder="Give people a summary of who you are and what kind of great stuff you can do for them."></textarea></div>'+
    '<div class="form-group"><label for="FType">Type of kitchen</label><select class="form-control" name="FType" id="FType"><option>--Select--</option><option>Type 1</option><option>Type 2</option><option>Type 3</option><option>Type 4</option><option>Type 5</option></select></div>',
    showCancelButton: false,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Update and Continue',
    cancelButtonText: 'Cancel',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-danger',
    buttonsStyling: false,
    focusConfirm: false,
    preConfirm: function () {

    //Set our Ajax variables in the start of preConfirm
    //We could've just made a form element as part of the html, and used a FormData class or form_name.serialize(). The current way is for illustration.
    var userPhone = $('#userPhone').val(), FName = $('#FName').val(), avgPrice = $('#avgPrice').val(), FInfo = $('#FInfo').val(), FType = $('#FType').val(), retData = [];

The above variables are all input values except for retData. 上面的变量是除retData之外的所有输入值。 retData is an array that will be used to store error strings that I receive from PHP. retData是一个数组,将用于存储我从PHP收到的错误字符串。 I can then tell JQuery to iterate through the array and display those errors as toastr notifications. 然后,我可以告诉JQuery遍历数组并将这些错误显示为toastr通知。 There are ways to do this with JSON, yes. 有几种方法可以使用JSON做到这一点,是的。

Here comes the meat and potatoes of what I am trying to get to. 这就是我要尝试的东西。 Now we can use Promise to continue to run our Ajax request with each user click, and leave the modal open until a certain condition is satisfied (all information is validated, and no errors). 现在,我们可以使用Promise在每次用户单击时继续运行我们的Ajax请求,并将模式保持打开状态,直到满足特定条件(所有信息都经过验证,并且没有错误)为止。

return new Promise(function (resolve) {
    //Run our actual ajax request inside the promise. Keeps the SWAL2 modal open
    $.ajax({
    url: prefix+'settings_val_first_modal.php',
    type: 'POST',
    data: ({userPhone: userPhone, FName: FName, avgPrice: avgPrice, FInfo: FInfo, FType: FType}),
    success: function(show) {

        retData.push.apply(retData, show.split(","));

        //Define the condition that keeps us in the promise.

        if(Number(retData[0]) === 0){

            //Remove the zero from our error array
            retData.shift();

            $.each(retData, function(i, val){

                //Display each array element as separate toastr notification
                toastr.error(retData[i]);

            });

        } else{

            //Define the condition that breaks us out of the promise
            resolve(true);

        }
    }
  });
});
}

Then, once that condition is met, we can move on down the modal chain using 然后,一旦满足该条件,我们就可以使用

}).then(function(result){

and doing whatever we want after that like adding in another swal for a picture upload, or saying thank you to the user with another swal. 然后执行我们想要的任何操作,例如添加另一只小牛以上传图片,或者对另一只小牛向用户表示感谢。

swal('You\'re all finished!','You now have full access to XYZ web app!','success');

then we make sure to define our dismiss function for our second modal. 然后确保为第二个模态定义消除函数。 In my case, an info swal modal: 在我的情况下,一个信息小模态:

}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
    if (dismiss === 'overlay') {
        swal(
            'Please Finish Your Profile',
            'You need to have a completed profile before you can start using XYZ web application',
            'info'
        );
    }
}).catch(swal.noop);

And there we have it. 我们终于得到它了。 I know this is a rather lengthy explanation, but I have found this kind of use to be most fitting for promises and SWAL2. 我知道这是一个冗长的解释,但是我发现这种用法最适合Promise和SWAL2。 Completing the code, we need to define the case that the first modal is dismissed. 完成代码后,我们需要定义第一个模态被取消的情况。

}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
    if (dismiss === 'overlay') {
        swal(
            'Please Contemplate Your Life',
            'Don\'t make me have to toggle this modal again! I\'d rather not!',
            'info'
        );
    }
}).catch(swal.noop);

Ultimately, I started with one goal which was - improve user experience. 最终,我从一个目标开始-改善用户体验。 Promises work here because otherwise, the modal would close after each button click, and a user would have to start down the entire chain again if they did something as simple as not include an @ with an email input or something. Promise在这里起作用,因为否则,该模式将在每次单击按钮后关闭,并且如果用户做了一些简单的事情(例如不包括带有电子邮件输入的@或类似内容),则用户将不得不重新启动整个链。

Promises let us keep a SWAL2 modal on screen until some condition is satisfied. 承诺让我们在屏幕上保持SWAL2模式,直到满足某些条件。 the condition could be anything, in my case it was form validation in PHP that returned strings to javascript. 条件可以是任何东西,在我的情况下,这是PHP中的表单验证,该字符串将字符串返回给javascript。 If the inputs were fine, the string is '1'. 如果输入正确,则字符串为“ 1”。 Otherwise the string contains something like '0,"Invalid Phone Number","An account is already associated with this email","etc"'. 否则,字符串包含诸如“ 0”,“无效的电话号码”,“帐户已与此电子邮件关联”,“等”之类的内容。 JQuery then makes an array, removes the leading zero, and outputs toastr notifications for each error in the array. 然后,JQuery创建一个数组,删除前导零,并为该数组中的每个错误输出toastr通知。

I hope this helps you in using SWAL2. 希望这对您使用SWAL2有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM