Show loader on AJAX – VueJS

Today, you will learn, how you can show a loader in VueJS when an AJAX is called. We will be using Axios library for calling AJAX request.

If you do not want to use Axios library, you can use the default XMLHttpRequest object of Javascript. Learn how to do it from here.

Video tutorial:

Let’s say we have the following code that:

  1. Includes VueJS and Axios library.
  2. Create a div for Vue app.
  3. Mount Vue app onto the div.
  4. On mounted, calls an AJAX request.
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app"></div>

And following javascript code will mount the Vue app.

Vue.createApp({
	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Now, I will create a loading text that will be displayed only if the loading variable is true.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app">
	<p v-if="loading">Loading...</p>
</div>

Then I will create that variable in my Vue app and initialize it as false.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Lastly, we are going to set this variable to true before calling the AJAX and false after the AJAX is finished.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		this.loading = true
		
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		this.loading = false
		
		console.log(response)
	}
}).mount("#app")

So that’s it. That’s how you can show a loader while AJAX is being called in VueJS.

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.