Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser.

While there are numerous examples available online, I am specifically looking to enhance my existing script by displaying a loading gif image while the data is being fetched during the 10-second refresh interval. I want the user to see a refreshing image like the one below:

.

Though this may seem straightforward, I have been unable to find relevant information on how to achieve this. Any suggestions or guidance on this matter would be highly appreciated.

Problem Statement:-

The following code snippet represents the div in my JSP file (dataInfo.jsp), where I aim to reload the container div every 10 seconds without having to reload the entire page.

<body>
    <div id='headerDivDash'>
        <h1 id='topHeaderDash'>
          <!-- some image here -->
        </h1>
    </div>
    <div id="vertical-list" style='display: block; list-style-type: none;'>
        <ul class="resp-tabs-list">
            <a href="_blank"><li>Test 1</li></a>
            <br />
            <a href="_blank"><li>Test 2</li></a>
        </ul>
    </div>

    <!-- just need to reload this div, other div should be intact without getting appended -->
    <div class="container">

    </div>
    <div class="footer">Some Value Here</div>
</body>

Below is the jquery script currently in use for loading the container div every 30 seconds, which is functioning correctly:

<script type="text/javascript">
    $(document).ready(function(){
        var auto_refresh = setInterval(
        function ()
        {
        $('.container').html('');
        $('.container').load('dataInfo.jsp .container').fadeIn("slow");
        }, 10 * 1000);

    });
</script>

Considering my earlier request, I am seeking a way to gray out the container div and display a refresh image during the ongoing refresh process. Once the refresh is completed, the normal content should reappear without the refresh image present.

Is it feasible to incorporate this feature into my current setup?

Answer №1

If you are utilizing JQuery already, this solution is perfect for your needs. You can employ the following code to establish a gray background and display a loading image.

// Implement a refresh function:
function refresh(){
    // SHOW overlay
    $('#overlay').show();
    // Fetch data:
    $.ajax({
        url: 'data.html',
        type: 'GET',
        success: function(data){
            // Extract only the container content on success
            var content =  $($.parseHTML(data)).filter(".container"); 
            // Replace content within the div
            $('.container').html(content);
            // HIDE the overlay:
            $('#overlay').hide();
        }
    });
}

$(document).ready(function(){
    // Create an overlay and append it to the body:
    $('<div id="overlay"/>').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: $(window).height() + 'px',
        opacity:0.4, 
        background: 'lightgray url(http://bradsknutson.com/wp-content/uploads/2013/04/page-loader.gif) no-repeat center'
    }).hide().appendTo('body');

    // Execute refresh at intervals:
    setInterval(refresh, 1 * 1000);
});

I hope this information proves to be beneficial. Please remember to replace "img/loading.gif" with the appropriate path to your preferred gif file.

Here is the functioning code snippet: http://jsbin.com/zizudexo/1/edit

Answer №2

As you initiate the ajax request, make sure to insert a loading image into the results container.

$('<div id="ajaxLoad"></div>').appendTo('.container');

To ensure it's displayed properly, apply this CSS rule:

#ajaxLoad {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: 0.5;
    background: silver url(my_image.png) no-repeat center center;
    z-index: 1000;
}

Include position: relative; in the .container CSS.

Next, proceed with the ajax call:

$.ajax({
    type: "GET",
    url: "dataInfo.jsp",
    success: function(data) {
        $('.container').html(data).fadeIn("slow");
    },
    complete: function() {
        $('#ajaxLoad').remove();
    }
});

Upon receiving the data, display it using the success function. The complete function will execute regardless of server errors or timeouts.

Answer №3

Have you checked out this: CodePen

In order to display a spinning refresh symbol, I utilized the

<i class="fa fa-refresh fa-spin"></i>
fontawesome icon... This method is effective in accomplishing your desired outcome...

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

Vue.js / Nginx / Node.js - Error 413: Payload Too Big

My frontend is built using Vue.js and is hosted on an nginx server in production. Here's a snippet of my nginx.conf configuration: server { listen 80; server_name localhost; root /usr/share ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

The media query designed for iPads with a minimum width will also be effective for Android devices

As I delve into the realm of editing CSS created by others, I come across a peculiar situation involving media queries specifically designed for iPads. While one query is intended for portrait orientation and another for landscape, they are causing havoc o ...

Animation will begin once the page has finished loading

On the website, there is a master page along with several content pages. The desired effect is to have a fade-in animation when navigating between pages. Currently, when clicking on a link, the new page appears first and then starts fading out, but this sh ...

What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not. ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Steps for passing a Javascript variable through POST method and then redirecting to a different page

I am facing an issue with sending a JavaScript variable via POST to a PHP page and displaying the new page. Despite checking the variable using Wireshark and confirming that it is sent correctly (key and value), the new page does not show anything. $(docu ...

Reverting Changes Made with JQuery Append

I have a table where each cell contains a button. When the button is pressed, it adds text to the cell. I am looking for a way to remove this text from the cell when the same button is pressed again. It's important to note that this button appears mul ...

Analyzing HTML markup to locate an anchor tag

While attempting to parse an HTML code using BeautifulSoup in order to retrieve a link that is hidden and does not appear on the website, I have encountered difficulties as it only retrieves links visible on the page. Is there a method to effectively par ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

What is the best way to adjust the height of a container to equal the viewport height minus a 300px height slider?

Forgive me for the rookie question, I know what I want to achieve should be simple but I seem to be having trouble articulating it in my search for solutions. Essentially, I am trying to set a section in HTML to the height of the viewport minus the height ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

Creating dynamically adjustable columns in Bootstrap

I've created a simple code for experimentation purposes: <!doctype html> <html lang='en'> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" ty ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Learn how to effortlessly update models by integrating AngularJS with Django and Django Rest Framework

Here is a JSON representation of a post based on its ID: http://127.0.0.1:8000/update/1?format=json {"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1} I am attempting to update the rating ...

Reading inputs from a Text Area using ko.JS databinding - Issue with capturing new lines

This is the code I have written for a text area: <div> <textarea data-bind="value: environment" rows="10" cols="20" class="form-group"></textarea> </div> I am looking to show the content typed in this text area in another DIV. ...

What is the best way to implement two for loops in a Django template to handle sending and receiving chat messages efficiently?

I am attempting to implement sending and receiving messages in a Django template using a for loop. Here is my views function: @login_required def message_form(request, id, slug, user_id): user2 = request.user user_id = user_id user = get_objec ...