Incorporate a loader when making an AJAX request and then conceal it after it has successfully completed

I find myself a bit puzzled here.

Currently, I'm developing a JavaScript form that sends values to a PHP page (submit.php). If the PHP page returns a success message, I plan to redirect the user to another page (success.php).

var url = 'submit.php';
var furl = 'success.php';
var formdata = new FormData();
formdata.append("name", 'John');
formdata.append('staffid',123);
formdata.append('csrf_test_name',csrf_token);

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) {
    uploadcomplete(event,furl);
}, false);
ajax.open("POST", url);
ajax.send(formdata);

function uploadcomplete(event,furl) {
    var response = event.target.responseText.trim();
    if(response=='Failed') {
        alert('Failed');
    } else {
        alert('Success');
        window.location.replace(furl);
    }
}

function showLoader(){
    document.getElementById('loader').style.display = 'block';
}

function hideLoader(){
    document.getElementById('loader').style.display = 'none';
}

However, I want to display a loading icon while the form data is being processed and hide it when the process is complete. To accomplish this, I have created two functions - showLoader() and hideLoader().

Now, my question is, where should I integrate these functions?

Answer №1

To utilize this functionality, link it with the readyState and the onreadystatechange event:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if(xhr.readyState === 0){ 
    displayLoadingAnimation(); 
  } else if(xhr.readyState === 4){
    hideLoadingAnimation();
  }
};

Alternatively, you can invoke them in your script like so:

var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(event) {
    processUpload(event, url);
    hideLoadingAnimation(); //<------------------hide the loading animation upon completion.
}, false);
xhr.open("POST", url);
displayLoadingAnimation(); // <------------------trigger the loading animation here.
xhr.send(formData);

Answer №2

This is how it should be executed:

During the request process:

ajax.addEventListener("progress", displayLoader);

Upon completion of loading:

ajax.addEventListener("load", removeLoader);

Answer №3

If you want to achieve this using Vanilla JavaScript, you can follow the steps below:

function fetchContent() {
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (request.readyState === 4 ) {
           if (request.status === 200) {
               removeLoader();
               // Add your custom logic here after receiving the response from the server
           }
           else {
               console.log('An error occurred...');
           }
        }
    };

    request.open("GET", apiEndpoint);
    request.send(formData);
    displayLoader();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The React onChange event fails to trigger

Why isn't the onChange event firing in the input tag? I used LinkedStateMixin to track the input value before, but now I want to add an onChange event to run a function. After removing LinkedStateMixin, the onChange event still doesn't fire. I ev ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

Utilizing a JavaScript function to toggle the Bootstrap dropdown without the need for manual clicking

I've configured a Bootstrap dropdown in my site's mini cart that includes a lightbox effect to grey out the background content when the dropdown is activated. Here's the code snippet: $(".dropdown").on('show.bs.dropdown hide.bs.dropdow ...

Pagination in Django - perform actions on all objects of all pages

Hello everyone, I am in the process of creating a web application using Django and am looking to replicate a feature that is available in the admin section of Django. Specifically, I want to have the ability to select objects on all pages and then perform ...

I'm facing an issue where I am only able to update the first record in the database using axios and Post

There seems to be a strange issue where only the first record in the database can be updated, even though all records can be retrieved without any problems. Here is the situation: https://i.sstatic.net/bK5aI.png To clarify further: Since names are unique, ...

Nested tables in Datatables retrieving child table rows based on parent table

I have been struggling for the past three days to get my nested Datatables working properly. I have a parent table called MAINtable and a child table called adjlinesTable. The issue I am facing is that all lines from the adjlinesTable are being drawn to ...

Leveraging the power of the wildcard feature to execute a variety of scripts when running

Inside my package.json file, I currently have the following scripts block: "scripts": { "test": "node tests/*-test.js" } In the tests folder, I have files named a-test.js and b-test.js. This can be confirmed by using the command ls tests/*-test.js. ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

I am in search of a JavaScript or jQuery plugin for an HTML slider with a unique range functionality

I've been searching online but couldn't find a slider like the one shown in the attachment. Can anyone help? Is there a way to create this specific slider or is there an existing plugin or library for it? Please refer to the image below :https:/ ...

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue? import question from './components/Questions.vue'; Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.App = new Vue({ ...

The Ajax function I'm using is not successfully sending data to the server-side

Below is a code snippet designed to collect data and send it to a PHP file. It successfully outputs the correct values when the button is clicked. var dataString = 'username='+SessionVars.my_username+'&lessonid='+SessionVars.my_les ...

Modifying the Trim Function in AngularJS

Using AngularJS version 1.5.6, I encountered a bug in my large application due to the default behavior of trimming input for text type inputs. Wanting to change this behavior globally without manually updating every textarea and text input element, I am se ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Incorporating transparent padding to PNG images for a three-dimensional effect

I'm currently facing an issue where I need to resize images to the Power of 2 in order to load them into Three.js. The resizing process involves a specific algorithm: var w = powerOf2Down(this.width); var scale = w / this.widt ...

The concept of a callback function is not applicable within the context of MongoDB in Node.js

I am encountering an issue while validating the existence of an email or username in my MongoDB users collection within Node.js using my User Model. Whenever I attempt to perform this validation, I receive an error stating callback is not a function. This ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...