Occasionally, a loading gif appears after a vanilla JS/AJAX call, but the output

While using AJAX to retrieve JSON data containing information on the next steps, I am implementing a CSS class hide/show to toggle images/wrapper and loading .png image.

However, even after toggling show/hide on the image, updating the image src, and adding/removing CSS classes on the new image, there are instances where the old picture briefly displays before transitioning to the new image src.

I attempted to introduce a 150-millisecond delay at the end, but the issue persisted.

function newImage(voteValue, imgValue, checked) {
    if (checked == "") {
        var innerVotingWrapper = document.getElementById('innerVotingWrapper');
        innerVotingWrapper.innerHTML = "You must select a category";
        console.log(checked);
    } else {
        var loadingWrapper = document.getElementById('loadingWrapper');
        var imgSrc = document.getElementById('imgSrc');
        var globalRating = document.getElementById('globalRating');

        globalRating.classList.add("hide");
        globalRating.classList.remove("show");
        imgSrc.classList.add("hide");
        imgSrc.classList.remove("show");
        loadingWrapper.classList.add("show");
        loadingWrapper.classList.remove("hide");

        var http = new XMLHttpRequest();
        var url = "pages/newImage.php";
        var params = "voteValue=" + voteValue + "&imgValue=" + imgValue + "&checked=" + checked;
        http.open("POST", url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.onreadystatechange = function () {
            if (http.readyState === 4 && http.status === 200) {
                var jsonData = JSON.parse(this.responseText);

                setTimeout(func, 1000);

                function func() {
                    console.log(this.responseText);
                    console.log(jsonData.checked);
                    loadingWrapper.classList.add("hide");
                    loadingWrapper.classList.remove("show");

                    if (jsonData.imgSrc) {
                        imgSrc.src = jsonData.imgSrc;

                    }
                    if (jsonData.id) {
                        var imgValue = document.getElementById('imgValue');
                        imgValue.value = jsonData.id;
                    }
                    if (jsonData.empty) {
                        console.log('No more images');
                        var innerVotingWrapper = document.getElementById('innerVotingWrapper');
                        innerVotingWrapper.innerHTML = "You have voted on all images, come back in 24 hours";
                    }


                    function showImg() {
                        globalRating.classList.add("show");
                        globalRating.classList.remove("hide");
                        imgSrc.classList.add("show");
                        imgSrc.classList.remove("hide");
                    }
                    setTimeout(showImg, 150);
                }
            }
        };
        http.send(params);
    }
}

Answer №1

The most effective solution in this situation is to re-create an image HTML tag.

Simply changing the image src does not prompt the browser to refresh it.

To create a new img tag, follow these steps:

var newImg = document.createElement("img");
newImg.src = jsonData.imgSrc;

Next, remove the old imgSrc and add the newly created newImg.

var parent = imgSrc.parentNode;
parent.appendChild(newImg);
parent.removeChild(srcImg);

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

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

Tips for locating the index while performing a drag and drop operation between two different containers

Can anyone help me figure out how to determine the exact index of an item when performing a jQuery drag and drop between two containers? I'm having trouble identifying the correct index, especially when it's dropped outside of its original contai ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

Determine if the user's intention is to tap or to scroll up and down the page on a touch-sensitive device

When a user taps outside of a popup-div (touchstart), the popup should be hidden. However, if the user's intention is to scroll/swipe (touchmove), the popup should not be hidden. Can you provide a code example that can detect and handle these two ac ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

The error encountered is related to the MongooseServerSelectionError that occurs in

I have been working on setting up my first mongo-db application to connect to the server. However, I am encountering a specific error during this process: const express = require('express'); const mongoose = require('mongoose'); const ...

The connection of <p:ajax> to a parent component that is not a ClientBehaviorHolder is not possible

Trying to trigger a function when selecting a value from a dropdown. See the code below: <h:form id="frmUpload" enctype="multipart/form-data"> <p:column><h:outputText value="Select Team: " /></p:column> <p:colu ...

Tips for validating an email address using ReactJS

I'm currently working on customizing the email verification process for a signup form in ReactJS. My goal is to replace the default email verification with my own validation criteria. Initially, I want to ensure that the entered email address contains ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Utilizing jQuery to dynamically update background colors within an ASP repeater based on the selected value of a dropdown list

On my asp.net web page, I have a repeater that displays a table with various fields in each row. I am trying to make it so that when the value of a dropdown within a repeater row changes, the entire row is highlighted in color. While I have achieved this s ...

Is it possible to dynamically change a form's input value using a JavaScript keyup function based on input from other form elements?

My form utilizes the keyup function to calculate the total value of 3 input fields by multiplying them and displaying the result. Below is a fiddle showcasing this functionality: $(document).ready(function () { $(".txtMult1 input").keyup(multInp ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

Learn the steps for showcasing user information in a tabular layout by utilizing session management with node.js, react.js, and SQL

This view page redirects users to their details Hello everyone, I am currently working on a project that includes two forms: login and user details. When a user logs in and fills out the details form, they should be redirected to a view page where they ca ...

How come my form submission continues to refresh the page?

I am new to the world of ajax and have a basic understanding of jQuery. Nonetheless, I am facing challenges while testing a simple ajax script. I have gone through similar questions for help, but unfortunately, I haven't been able to find a solution y ...

What is the correct method for dynamically importing framer-motion in NextJS?

I am currently utilizing framer-motion in my NextJS project. My goal is to import {motion} using Next's dynamic import method. However, I am encountering difficulties as it does not seem to function properly. import { motion } from "framer-motion ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

The functionality of JQuery's ajax post request is not functioning properly as intended

Link to the page: localhost/mysite/create-user This is the block of code: <form class="form-horizontal" name = "signUp1F" id = "signUp1F"> <input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = ...

"Combining AngularJS with Material Design disrupts the functionality of infinite scroll

Issue: Infinite scroll is loading all pages at once instead of waiting for the user to scroll to the page bottom. Environment: AngularJS 1.3.17 Materials Design 0.10.0 Infinite scroll script: https://github.com/sroze/ngInfiniteScroll Demo being used: The ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...