0

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

Fid
  • 462
  • 4
  • 21
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Ivar Jun 15 '22 at 14:12
  • @Ivar I don't believe so. If the variable `code` is `FOO1234`, the script just posts the data, which is correct. If however `code` is `ABC1234`, the Sweet Alert popup asks the user to provide the "secondary code". I just need it to stop for the user input, then continue as it would in the first case. – Fid Jun 15 '22 at 14:17
  • I understand. The duplicate should explain why it doesn't work the way you are doing it and should provide a way around it. This is the very core of how JavaScript works (and one of the most commonly asked questions here on SO), so putting some time in understanding it isn't a waste. :) You should be able to rewrite this using `async`/`await` to make it work. `swalBs.fire()` already returns a Promise that you can `await`. – Ivar Jun 15 '22 at 14:21
  • swal is non-blocking - ie your code will continue after the swal and the "yes" code "continues" in the callback/then. Move your "continue" code to another function and call it from the callback and from the case where swal is not needed/wanted. – freedomn-m Jun 15 '22 at 15:48

0 Answers0