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

Passing PHP Variables Between Pages

I'm currently working on building a game using html5(phaser js) and I need to create a leaderboard. Here's the code snippet I have: restart_game: function() { // Start the 'main' state, which restarts the game //this.game.time.events ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

Getting POST data in Next.js is a common task that requires understanding of how the

I am currently working on a form validation project using the App Router within Next.js. // app/register/page.tsx export default function Register(context: any) { console.log("Register page", context.params, context.searchParams); return ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...

When sorting in AngularJS using the orderBy filter, remember that string values should come before numeric values: for example, sort as follows (n/a, 0,

While running an AngularJS filter sorting on a table, I encountered an issue where if the value is 'n/a' (which is a numeric string), the sorting is incorrect. I expected the order to be n/a, 0, 1, 2, 5, 100 since strings should be considered l ...

scrapy css last-child selector unable to target text

I am currently facing a challenge in selecting and matching elements within an HTML document using CSS selectors in the Scrapy framework. My issue lies with extracting information from a specific field using the last-child selector. Below is the snippet o ...

Using Python to fetch information from a web application

I'm currently working on automating a reporting process using Python. The goal is to log in to a specific page and extract the URL: which can be seen in the screenshot below. However, if you view the page source, it only shows the HTML code (with not ...

reveal a hidden div by sliding it during an onclick action

My PHP while loop code is as follows: while (...($...)){ $convid = $row['ID']; echo" <button onclick='getconvo($convid)'>open</button> <div class="convowrap"></div> "; } Here is the correspond ...

Managing paths for JavaScript and CSS scripts using Jquery Ajax for both direct and remote access

When using Jquery Ajax, I have a main entry script called "index.php." This script allows the user to request "/folder2/index.php" using ajax. I also use the same path "/folder2/index.php" for direct access. However, because of the ajax call, I need to ...

Repeated firing of jQuery's Ajaxstop within a click event

When using the quantity plus button on the woocommerce cart page and reaching maximum stock, I want to display a notice. However, due to an auto update on the cart, I have to wait for the ajax load to complete before showing the notice. My script revealed ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

Showing the json encoded array received from an ajax response

I have encountered this data result {"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18& ...

Bourbon encountering difficulty with font-face mixin in Rails version 3.2.2

After watching Ryan Bates' screencast on Bourbon, my application.css.scss file looks like this: @import "bourbon"; @import "main"; @import "events"; ..etc. In my main.css.scss stylesheet, I am able to use the @include transition() mixin without any ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions fo ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Capture and save video footage from Scriptcam's webcam recording feature

I'm in search of a solution similar to the one provided on this post (I have the same issue): How to save files in my server with ScriptCam plugin Unfortunately, that solution doesn't seem to work for me. I have implemented the scriptcam plugin ...

What is the best method for creating an HTML table using a JSON object?

Currently, I am in the process of developing an express app that can render a csv file and convert it into a json format. Within my method, I have this json data stored as a variable and my goal is to display it as a table on an HTML page. How can I effect ...

What is the process for uploading images in the backend of a Next.js API?

I am working with Next.js and an API. I need to be able to upload two files and include one text input field using the API backend. I have been struggling to find a solution for uploading files with different fields along with a single text input field in ...