Error encountered: Loader fails to display during AJAX request

Currently, I am facing an issue with a JavaScript function that triggers an AJAX call to fetch some data when there is a change in a select list event.

I have experimented with various methods to display a loader while the data is being fetched, as the current situation where the select list pauses doesn't look appealing to customers.

However, regardless of how I attempt to display the loader, it always appears after the AJAX call has completed. Here's the snippet of my current code:

<select name="addresslist" class="form-select" id="edit-addresslist" onchange="selectAddress(this)">
<option value="none">-- Please select an address from the list below --</option>
//additional options are not relevant here       
</select>

JS File

function selectAddress(data) {
var loader = document.getElementbyId('overlay-loader');
var selectedAddress = data.value;
var uprn = selectedAddress.split(',')[1];

loader.style.display = "block";

$.ajax({
    url: '~/collectiondates',
    async: false,
    data: {
        uprn: uprn
    },

    success: function (data) {

        result = data;
}

Despite trying different approaches such as calling a separate function on the "onchange" event or within selectAddress, none seem to work as the AJAX function always completes first before displaying the loader, leading to an unnecessary delay.

Fortunately, the rest of my code functions properly as intended apart from this loading issue.

Any insights or suggestions would be greatly appreciated. Thank you.

Answer №1

Greetings! I recommend utilizing deferred promises such as done, fail, and always in conjunction with your ajax call. You can also include a setTimeout if the request is particularly fast. Feel free to refer to the example I have created in this JSFiddle. Here is a sample syntax:

$( function() {
  function makeAjaxCall(id, status, comment){
    return $.ajax({
      url: 'request.php',
	  data: {
        id: id,
        requisitionStatus: status,
        comment: comment    
      },
      type: "POST",
      cache: false,
      beforeSend: function() {
        $("#requisitionStatusDialog").dialog('close');
        $('#ajax_loader_my').show();
      }
    })
  }

  $( "#requisitionStatusDialog" ).dialog();

  $("#yourbuttonInputId").on('click',function(event) {
    makeAjaxCall().done(function(data,response){
      var obj = JSON.parse(data);
      if (obj.status == "success") {
        alert('We have completed the task!');
      }
    }).fail(function(data,response){
      $("#updateDialog").dialog(' close');
    }).always(function(data){
      if(confirm('You have finished the request. Click OK to continue, or Cancel to reload the page.'))
      {
        $('#ajax_loader_my').hide();
        $("#requisitionStatusDialog").dialog('open');
      }else{
        location.reload();
      }

    });
  });
} );

I hope you find this information helpful! =)

Answer №2

To potentially combat any speed issues with the backend, consider wrapping your AJAX code in a setTimeout function.

setTimeout(function(){
    // Add your AJAX logic here
}, 2000); // Delay execution by 2 seconds

Answer №3

It might be appearing later because the CSS is not set to hide after success or error occurs. If you're concerned about the loader not showing before the AJAX call finishes, you can introduce a delay using the setTimeout function. Here's my approach:

<select name="addresslist" class="form-select" id="edit-addresslist" onchange="selectAddress(this)">
<option value="none">-- Please select an address from the list below --</option>
//there are more options but this isn't important here       
</select>

JS/JQ:


function selectAddress(data) {
    openloader();
    var selectedAddress = data.value;
    var uprn = selectedAddress.split(',')[1];

    $.ajax({
        url: '~/collectiondates',
        async: false,
        data: {
            uprn: uprn
        },

        success: function (data) {
            closeloader();
            result = data;
        }
     });
}

function openloader(){
    $("#overlay-loader").show();
}

function closeloader(){
    $("#overlay-loader").hide();
}

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

What is the integration process of using Font Awesome with React?

After installing react-create-app using npm, I also added react-fontawesome. Now, I'm wondering how to include the css styles of fontawesome in my project? Here is a glimpse of my work space: https://i.stack.imgur.com/pM1g1.png ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

jQuery dynamic id selection

I'm facing a challenge with dynamically generated forms that have dynamically generated IDs and potentially classes. Although the forms are identical, they each have a unique ID at the end. How can I target and manipulate each set of inputs individua ...

Troubleshoot: Json causing issue with displaying markers on Google Maps API (v3)

I developed a custom Google Maps application using JSON data and implemented PostgreSQL database integration. Here is the code snippet: <script type="text/javascript"> var map; var national = [{"lng":"-6.173319","city":"JAKARTA","lat":"106.818 ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

Error: Trying to access "dishes" property on an undefined object gives a TypeError

Need Assistance Urgently! I have developed a web application using react and integrated it with node js. In the app, I am required to pass the status of a dish to the DishDetail Component indicating whether it is marked as "Favorite" or not. If a dish is ...

Encountering difficulties accessing Node.JS Sessions

Hey there, I am currently working on integrating an angular application with Node.js as the backend. I have set up sessions in Angular JS and created my own factory for managing this. Additionally, I am utilizing socket.io in my Node.js server and handling ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

Executing functions after the completion of a CSS animation

I am currently utilizing Vue3. I have implemented a feature where the box grows in size when the mouse hovers over it. .curl:hover { width: 200px; height: 200px; } I am looking for a way to notify the user once the animation is complete and the size has ...

Combining the recorded video feed from two HTML5 canvases

In the process of creating a whiteboard app for a web conferencing platform, I have found that most libraries use 2 separate canvases - one for drawing on the top and another for storing older drawings at the bottom (to improve performance by clearing the ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...

Ways to display an SVG spinner prior to a substantial UI refresh

I am currently facing an issue with updating 10 apexcharts bar charts simultaneously in a Vue app. When this process occurs, it takes approximately one second to load completely, and during that time, I would like to display an svg spinner. However, the co ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Tips for compressing JavaScript on the fly

Is there a method to dynamically compress JavaScript, similar to how gzip functions for HTML (and apparently CSS)? I'm looking for a solution where I don't have to manually compress the file before uploading every time. I want the server to hand ...

Retrieving an HTML page from one location and automatically populating textboxes with preexisting values on the receiving end

I'm currently facing a dilemma. Here's the issue: I need to load an HTML page (let's call it test.html) when a button is clicked on another page (referred to as home page). The test.html page has input boxes that I want to populate with p ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

The error message is indicating that the function "req.assert" is not

Can you identify the issue with this code snippet (express 4.16.0, TypeError: req.assert is not a function)? userController.signupPost = function(req, res, next) { console.log(req.body); var express=require('express'); var validator = require(&a ...

Struggling to retrieve information from a template and transfer it to a controller in AngularJS

Currently, I am encountering issues with user authentication in my template. Oddly enough, everything works fine when testing with Postman. Firstly, I initiate an API call to /users/authenticate to retrieve a token. Next, I verify the token by making anoth ...

Difficulty in accessing JSON data with Node.js

Encountering difficulties with retrieving JSON data from a JSON file, I am faced with the following error message: "NetworkError: 404 Not Found - http://localhost:8000/channels.json" Below is the code snippet used to fetch JSON data in my HTML file: ...