AJAX in Sweetalert 2

In this article, I am going to teach you, how you can use AJAX in sweetalert 2. As per sweetalert 2 documentation, you can use Fetch API for calling AJAX requests. Fetch API is good, but not for more control over your request, like using POST method, adding headers etc. Fetch API is not so suitable in those cases.

Video tutorial:

AJAX in Sweetalert 2

Following is your code that you get from sweetalert 2 documentation:

Swal.fire({
  title: 'Submit your Github username',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Look up',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`//api.github.com/users/${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire({
      title: `${result.value.login}'s avatar`,
      imageUrl: result.value.avatar_url
    })
  }
})

Replace that with the following function:

swal.fire({
	title: 'Submit your Github username',
	input: 'text',
	inputAttributes: {
		autocapitalize: 'off'
	},
	showCancelButton: true,
	confirmButtonText: 'Look up',
	showLoaderOnConfirm: true,
	preConfirm: (login) => {

		return new Promise(function (callback) {
			const ajax = new XMLHttpRequest()
			ajax.open("GET", "https://api.github.com/users/" + login, true)

				ajax.onreadystatechange = function () {
					if (this.readyState == 4 && this.status == 200) {
						callback( JSON.parse(this.responseText) )
					}
				}

			ajax.send()
		})
		
	},
	allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
	if (result.isConfirmed) {
		swal.fire({
			title: `${result.value.login}'s avatar`,
			imageUrl: result.value.avatar_url
		})
	}
})

You can notice that the fetch() function has been replaced with a Promise. But now you can use XMLHttpRequest and have more control over your AJAX requests.

Learn more about promises from here.