Fusseldieb
Fusseldieb

Reputation: 1374

AJAX call with error catching in SweetAlert2

I'm scratching my head for a couple of days now and I can't get SweetAlert2 to do a AJAX call and return "Success" if it succeeded or show me an error in the same box if something goes wrong, leaving the user free to try again.

My implementation is following so far. The problem is that it shows the error in the box, but closes it at the same time:

swal({
  title: 'Submit?',
  text: 'Are those informations correct?',
  type: 'question',
  showCancelButton: true,
  confirmButtonText: 'Absolutely',
  cancelButtonText: 'Not sure',
  showLoaderOnConfirm: true,
  preConfirm: function() {
    return new Promise(function(resolve,reject) {
      $.ajax({
        url: '*****', // Invalid URL on purpose
        type: 'POST',
        data: {test: true}
      })
      .done(function(data) {
        resolve(data)
      })
      .fail(function() {
        reject()
      });

    })
  },
  allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
  if (result.value) {
    swal({
      title: `Success`,
      text: result.value
    })
  }
}).catch((result) => {
  swal.showValidationError('POST failed. Please try again.');
})

In the documentation I cannot find a AJAX call with a showValidationError. The closest I found is a fetch() call, but those are only for GET, as far as I know.

I also tried something like: return true, return false, throw new Error, promises inside promises, but that was all trial-and-error, so I came here.

I also made a fiddle: https://jsfiddle.net/xpvt214o/306267/

Thanks in advance for any help and/or suggestions.

Upvotes: 0

Views: 3728

Answers (1)

Fusseldieb
Fusseldieb

Reputation: 1374

After one more day I figured it out. I had to .then and .catch the $.ajax and attach swal.showValidationError on it in order to work.

On a AJAX error it will show following in the same box now (The user can try as many times as he pleases):

On error

On success following:

On success

swal({
  title: 'Submit?',
  text: 'Are those informations correct?',
  type: 'question',
  showCancelButton: true,
  confirmButtonText: 'Absolutely',
  cancelButtonText: 'Not sure',
  showLoaderOnConfirm: true,
  preConfirm: () => {
    return $.ajax({
      url: '***',
      type: 'POST',
      data: 'test'
    })
    .then(response => {
      return response
    })
    .catch(error => {
      //console.log(error); // Nice to view which properties 'error' has
      swal.showValidationError(
        `An error ocurred: ${error.status}`
      )
    })

  },
  allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
  if (result.value) {
    swal({
      type: 'success',
      title: 'Success',
      text: result.value
    })
  }
})

Fiddle: https://jsfiddle.net/z3kfhsj8/6/

Upvotes: 3

Related Questions