Pause for the completion of a function before triggering a second function (such as loading a page) that will only start once the previous function has finished

Is there a way to show a loading sign while the Post() function is in progress?

function Post() {

    // 1. Creating XHR instance - Starting
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } else {
        throw new Error("Browser does not support Ajax");
    }
    // 1. Creating XHR instance - End

    // 2. Defining response handling for XHR - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('new_story_post').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Defining response handling for XHR - End

    var textid = document.getElementById("textid").value;

    // 3. Sending post request with loading feedback - Start 
    xhr.open('POST', 'post.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Display loading sign here
    
    xhr.send("textid=" + textid);
    // 3. Sending post request with loading feedback - End
}

Answer №1

You're probably already utilizing this in your code. Take a look at the documentation regarding the onreadystatechange event.

Each time the readyState changes, the onreadystatechange event is triggered, with the readyState property indicating the status of the XMLHttpRequest.

I hope this information proves helpful.

Edit: See an example here

xmlhttp.onreadystatechange = function () {

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

        $("#loading").append('Loaded. Status is ' + xmlhttp.readyState + '<br />');

    } else {

        $("#loading").append('Working... Status is ' + xmlhttp.readyState + '<br />');
    }
}

Answer №2

Process

  • Start by showing a loading indicator while waiting for the response from your service.
  • Hide the loading indicator once the service has provided a response.

Steps to Follow

Here is how you can update your function:

function Post() {
  // Step 1: Display the loading indicator
  document.getElementById("loading-overlay").style.display = "block";

  // Step 2: Create XHR instance
  // ...

  // Step 3: Response handling 
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status == 200 && xhr.status < 300) {
        document.getElementById('new_story_post').innerHTML = xhr.responseText;
      }

      // Hide the loading indicator regardless of the response
      document.getElementById("loading-overlay").style.display = "none";
    }
  }

  // ...
}

Include the loading indicator in the body:

<div id="loading-overlay">Loading...</div>

Add some styling with CSS:

#loading-overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  text-align: center;
  display: none;
}

Additional Tip

You might consider using a callback function for better code organization and flexibility.

function Post(textid, fn) {
  // Step 1: Create XHR instance - Start
  var xhr;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Msxml2.XMLHTTP");
  } else {
    return fn(new Error("Ajax is not supported by this browser"));
  }
  // Step 1: Create XHR instance - End

  // Step 2: Define response handling - Start
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status == 200) {
        fn(null, xhr.responseText);
      } else {
        fn(new Error('Request failed'));
      }
    }
  };

  // Step 3: Specify action, location, and send data to server - Start 
  xhr.open('POST', 'post.php');
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send("textid=" + textid);
  // Step 3: Specify action, location, and send data to server - End
}

Usage example:

// Show loading indicator
document.getElementById("loading-overlay").style.display = "block";

// Obtain textid value
var textid = document.getElementById("textid").value;

// Call the Post function
Post(textid, function(err, res) {
  if (err) {
    // Handle errors
  } else {
    // Hide loading indicator
    document.getElementById("loading-overlay").style.display = "none";

    // Update the view
    document.getElementById('new_story_post').innerHTML = res;
  }
});

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

Searching for a specific value in a string using Javascript and then displaying

I am working on a react typescript project where I have an array called result that contains a URL with the format /Items(142)/. My goal is to extract the item ID from this URL and store it in a variable. I am aware of using something like result.data.oda ...

Unsuccessful Execution of Plain Javascript within Angular CLI Component

I am in the process of developing a website using Angular CLI. I am attempting to implement something similar to this example : https://codepen.io/chrisdoble/pen/WQLLVp Is there a way to write plain JavaScript in component.ts. Here is my JavaScript : ...

Validating ReactJS properties

Transitioning from ReactJs to React-Native, I came across this function structure in a react-native button code by Facebook: class Button extends React.Component<{ title: string, onPress: () => any, color?: ?string, hasTVPreferredFocus?: ?bo ...

Using three.js to detect mouseover events exclusively on objects, rather than on the

I am a newcomer to Three.js and I am attempting to display tooltips only on cubes or blocks. Fortunately, I found a helpful resource at . However, I noticed that the tooltip changes color and text on background checkboxes as well, which is not what I want ...

Determine the location of an element within a scrolling container using jQuery and automatically scroll to that location

Hey there! I've got a list of items (users) in a popup that's contained within a scrollable div. What I'm trying to achieve is creating a search box using jQuery and Javascript to determine the position of a specific user in this list and th ...

Display the image title in a separate div when hovering over it

As a beginner in jQuery, I am working on creating a gallery that displays the title attribute of an image in a separate div when hovering over the image. The title should disappear when the mouse moves away from the image. I hope that explanation is clear! ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

Storing JSONP data in a variable: Tips and Tricks

Having an issue with storing JSONP data into variables and using it as input for a Google Pie Chart. Consider the following: Data in test.json: { "name": "ProjA", sp": 10, "current": 20 } The goal is to retrieve the SP value. Attempted solution usin ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...

Dynamically load values for AJAX functions

I am working on a dynamic list of strings that are generated through an AJAX call. Here is the function I am using: function updateIngredients(boxId, prodid) { $.ajax({ type: "GET", url: "/Products/FetchBoxIngredients?idbox ...

Tips for loading data without disrupting the current scroll position

When data is prepended in a given set, why does the scroll position change? I notice that when I scroll to the top and prepend new data, the scroll position goes back up. However, on platforms like Facebook and WhatsApp, the scroll position remains the sam ...

Using Node.js with Express, the Router.use() method expects a middleware function as an argument, however, it received a different type: ' +

As I delve into the world of back-end development using node and express, my current project involves creating a back-end for a simple blog with posts and user authentication. This will be utilized later in an angular 4 application. While testing the "Pos ...

Enhance your projects with the power of React Bootstrap and React.PropTypes validation

I've set up a Rails 5 application with browserify and react-rails. While I can load components and install packages via npm, the browser console shows 'Warning: You are manually calling a React.PropTypes validation function for the....' when ...

Checkbox values are not being properly returned in the AJAX post request

var selectedValues = $('input:checkbox:checked').map(function() { return this.value; }).get(); $.ajax({ type: 'POST', url: 'showdata.php', data: {values : selectedValues}, success: function(response) { // Only t ...

Loading/Adding JS script in an asynchronous manner

In my Laravel project, I am implementing templates for different pages based on a main page. Each page requires different JS scripts to function properly, so I created a template to import these scripts: <!-- jQuery 2.1.3 --> <script src="{{ URL: ...

What methods do Web Applications use to interface with a server?

If I wanted to develop a collaborative web application where users can simultaneously work on a diagram, how would the client and server exchange messages? Here are some details and an illustration of how the system is intended to function: https://i.stac ...

Get node extensions set up without the hassle of typing in commands

As part of my internship, I am tasked with setting up a node server for the company. I have successfully installed Node on my Windows computer and now need to install plugins such as:    - nodejs-webpack    - colors &n ...

Issue with Angular $http post method in sending data to PHP script on server

In my application, I have a PHP service located at api/add. This service accepts rq and name parameters via POST. The rq parameter determines the function to perform, with addCity being an example function that inserts a city into the database, where name ...

Is it possible to utilize the output of a function nested within a method in a different method?

I am currently facing a challenge with my constructor function. It is supposed to return several methods, but I'm having trouble using the value from this section of code: var info = JSON.parse(xhr.responseText); Specifically, I can't figure ou ...

Protractor Error: Identifier Unexpectedly Not Found

I've encountered a slight issue with importing and exporting files while working on Protractor tests. HomePage.js export default class HomePage { constructor() { this.path = 'http://automationpractice.com/index.php'; this.searchQ ...