0

I have this code using ajax

    $.ajax({
        url: '/shipments/courrier/get',
        type: 'GET',
        beforeSend: function (request) {
            return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
        },
        success: function(response){
            let inputOptionsPromise = new Promise(function (resolve) {
                console.log(response);

                setTimeout(function () {
                    resolve({
                        '#FF0000': 'Red',
                        '#00FF00': 'Green',
                        '#0000FF': 'Blue'
                    })
                }, 2000)
            })
        }
    });

response has data returned

[{id: 1, name: "DHL", link: "https://webtrack.dhlglobalmail.com/?trackingnumber=",…},…]
0 : {id: 1, name: "DHL", link: "https://webtrack.dhlglobalmail.com/?trackingnumber=",…}
1 : {id: 2, name: "LBC", link: "https://www.lbcexpress.com/track/?tracking_no=",…}

but the problem, I don't have idea how to put it on resolve()

setTimeout(function () {
    resolve({
        '#FF0000': 'Red',
        '#00FF00': 'Green',
        '#0000FF': 'Blue'
    })
}, 2000)

replacing this values

'#FF0000': 'Red',
        '#00FF00': 'Green',
        '#0000FF': 'Blue'

Anyone can give me better solution for this?

Fil
  • 8,225
  • 14
  • 59
  • 85

1 Answers1

1

Based on the link you posted in the comments (SweetAlert dropdown dynamically add items in list , for reference), it seems you want to populate a SweetAlert with the results of your AJAX call. Since SweetAlert supports providing a Promise object as the "options" parameter, and since jQuery $.ajax() returns an object which implements the Promise interface, you can easily combine these two things:

var optionsDataPromise = $.ajax({
        url: '/shipments/courrier/get',
        type: 'GET',
        beforeSend: function (request) {
            return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
        }
    });

swal({
  input: 'select',
  inputOptions: optionsDataPromise
})

In this example, we assigned the Promise returned by $.ajax to the optionsDataPromise variable, and then gave that variable to swal() as the inputOptions parameter. When the Promise resolves - which, as you might guess, happens when the AJAX call returns successfully - then the alert will be populated with options based on the data returned from the AJAX call.

P.S. The example in that link was just a static Promise designed to imitate the behaviour of a useful Promise (such as an AJAX request). Since it always returns the same data, which could just have been placed directly in an object, it doesn't intrinsically achieve anything useful, it's not a construct to copy directly.

ADyson
  • 57,178
  • 14
  • 51
  • 63