Displaying a loading animation to keep users engaged while AJAX calls retrieve data from the server

My issue was outlined in a recent discussion on Stack Overflow. In essence, my goal is to display a loading indicator before server-side processes complete: [Loader] -> [Target page]. However, the HTML content loads after the server-side tasks, resulting in the loader being displayed after a blank page: [Blank page] -> [Loader] -> [Target page].

I received valuable advice suggesting the use of AJAX. Although I am not very familiar with AJAX, I conducted research and wrote the following code snippets.

Here is a snippet of the HTML code (sample.html),

<body>
    <!-- Loading image  -->
    <div id="loading">
        <img id="loading-image" src="/img/loading.gif" alt="Loading..."/>
    </div>
    
    <section id="content">
        <span th:text="${data_list}"></span>
    </section>

    <script type="text/javascript">
        var $loading = $('#loading').hide();
        $(document)
          .ajaxStart(function () {
            $loading.show();
          })
          .ajaxStop(function () {
            $loading.hide();
          });
         
        $.ajax({
            url: "/dataSend",
            type:"POST",
        }).done(function (fragment) {
            
        });
    </script>
</body>

And here is part of the Java code (Controller.java).

@RequestMapping( method = RequestMethod.GET, path = "sample")
String loadSample(Model model) {
    return "sample";
}

@RequestMapping(method = RequestMethod.POST, value = "/dataSend")
String sendData(Model model) {
    model.addAttribute("data_list", service.getAllData());
    return "sample :: #content";
}

Currently, I'm facing a roadblock. If anyone can assist me in resolving the code issue or provide relevant examples, I would greatly appreciate it.

Answer №1

One possible solution to your problem is as follows:

<script type="text/javascript">
    var $loading = $('#loading').show();
     
    $.ajax({
        url: "/dataSend",
        type:"POST",
    }).done(function(fragment) {
        $('#loading').hide();
    });
</script>

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

Retrieving data in String format using Jersey client

I am currently working on developing JUnit tests for a REST client that utilizes Jersey. As part of this process, I require a means to obtain a duplicate of the data being sent to the server in order to run comprehensive tests within JUnit. At present, my ...

Having difficulty positioning the dropdown above the other elements in the body

Below, you'll notice that the dropdown menu isn't positioned correctly over other body elements like the timer. I'm utilizing bootstrap for the dropdown and redcountdown js for the timer. https://i.sstatic.net/OO8Jm.png Here is the HTML: & ...

How to safely add multiple objects to an array in TypeScript & React without replacing existing objects - Creating a Favorites list

I'm in the final stages of developing a weather application using TypeScipt and React. The last feature I need to implement is the ability for users to add queried locations to a favorites list, accessed through the "favorites" page. By clicking on a ...

Selenium in Java is unable to send keys or click on elements

I am attempting to login to this specific website Below is the code I am using : driver.findElement(By.id("userid_sebenarnya")).sendKeys("myUserName"); This is the property for the input text field with id='userid_sebenarnya' <div class="f ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

Issue with Android mobile navigation: NavController Action class not being created

In my mobile app, I am utilizing the NavController to navigate between fragments. I have set up two navigation options in the mobile_navigation.xml file, but I am struggling to access the generated Action class. Hopefully that makes sense. On my screen, ...

How to write an aggregation query in Java using the MongoDB driver version 3.4?

Can someone assist me in writing the equivalent Java query for driver version 3.4 of this aggregation query: db.getCollection('MYTABLE').aggregate([ {"$match": { "ID_STATUSMATRICULA": 1 } }, {"$group": { "_id": null, ...

Is there a built-in event in Jquery UI tabs for when the tabs are collapsed?

Which event in jquery ui can I utilize to detect when a panel collapse has finished on the browser? I require this information to perform calculations based on the screen layout after the collapse has occurred. If I use the select or show event callbacks, ...

Slider Jquery - Displaying Half-Step Visual Bar Lengths

JSFIDDLE $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 5, min: 0, step: .5, max: 10, slide: function( event, ui ) { $( "#amount" ).val(ui.value); ...

Enhancing Win8 apps with AppendTo/jquery-win8

Recently, I've been intrigued by the ToDoMVC samples and decided to try porting them into a Windows 8 JS app. I thought it would be as simple as copying and pasting the code while making sure to reference the necessary WinJS libraries. However, I soo ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

Is the program's response is null upon execution?

After developing a program and ironing out run-time errors, I encountered a new issue - the program is not displaying any output when executed. The main functionality of the program involves merging data from two files to create a list of classes with cor ...

I am encountering difficulties with importing Node modules into my Vue.js project

Having some trouble importing a node module via NPM in a Vue.js single file component. No matter which module I try to install, it always throws an error saying These dependencies were not found. I'm following the installation instructions correctly ( ...

Enhancing your Selenium automation scripts with linkText and partialLinkText locators: Handling multiple occurrences of identical text

Is there a method to find the second (or third, fourth, etc.) link on a page using By.partialLinkText or By.LinkText? I am looking to locate multiple links that include the same "partial text." Ideally, I want to use a while loop to find the first, then t ...

Vue component fails to render on a specific route

I am having trouble rendering the Login component on my Login Route. Here is my Login component code: <template> <v-app> <h1>Login Component</h1> </v-app> </template> <script> export default { } </script ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

Vuetify's scrolling list feature allows for smooth navigation through a list

Check out my Vuetify code snippet that utilizes a list: <v-list> <v-list-tile v-for="user in users" :key="user.id" avatar @click="" > <v-list-tile-content> < ...

The post() method in Express JS is functioning flawlessly in Firebase cloud function after deployment, however, it seems to encounter issues when running on a

https://i.stack.imgur.com/bIbOD.pngI am facing an issue with my Express JS application. Despite having both post() and get() requests, the post() request is not working on my local machine. It keeps throwing a 404 error with the message "Cannot POST / ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...