Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there,

I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on.

Currently, I have an image displayed in an HTML page like this:

<div id="tag_sunrise_sunset"><p><img src="assets/icons/sun_icon.png" alt="" width="14" height="14">&#8593; 06:25 &#8595; 20:33</p></div>

Additionally, I am invoking the following function every half second:

/******************************************
* Obtains the most recent data from the database
******************************************/
// Global variables
var AutoScript = false;
var ValueCheck = -1;
var ControlUpdate = "";      
var ThermostatManualUpdate = false; 
var DebugMode = false;

function getDataFromDatabase(j)
{ 
    var complete = false;
    var json=$.parseJSON(j);
    var techname = "";
    var techname1 = "";
    var valuetf;
    var typecomp;
    var value01;
    var c;
    var w;

    $(json).each(function(i,val){
    $.each(val,function(k,v){

    if (DebugMode)
    {
        console.log ("k = " + k);
        console.log ("v = " + v);
        console.log ("----------------");
    }

    switch (k)
    {
        case "tech_name":
        techname = v;
        techname1 = "#" + v;
        break;

        case "value_t_f":
        valuetf = v;
        break;

        case "compo_type":
        typecomp = parseInt(v);
        complete = true;
        break;

        default:
        break;
    }

    if (complete)
    {
        if (DebugMode)
        {
            console.log ("My name is " + techname + " (" + techname1 + ")" + " I am of type " + typecomp + " and my value is " + valuetf);
        }
        complete = false;               

        // Component types              
        // Note: simplified structure of the if statements [check ? value_if_true : value_if_false;]
        c=document.getElementById(techname);

        if (c===null)           
        {
            if (DebugMode)
            {
                console.log("Component " + techname + " does not exist");
            }
        }
        else
        {
            switch (typecomp)
            {
                case 1:         
                case 2:         
                    (valuetf > 0) ? value01 = 1 : value01 = 0;                      
                    (c.checked) ? w = 1 : w = 0;

                    if (value01 != w)
                    {               
                    
                    (value01 == 0) ? uncheckBox(techname1) : checkBox(techname1);
                    }
                break;

                case 3:        
                break;

                case 4:        
                break;

                case 5:        
                break;

                case 6:       
                var ctrl = techname;
                document.getElementById(ctrl).value = valuetf;

                c=document.getElementById("prg01");
                c.value = valuetf;
                break;

                case 7:          
                break;

                default:
                console.log("other");
                break;
        }
    }
    }
    });
    });
}

My intention is to display a different image based on the value of the variable 'w'. Is there a straightforward way to accomplish this using Ajax, or is it not suitable for this purpose?

Apologies if this question seems trivial, but I find myself at a standstill. Also, I acknowledge that there are likely areas for improvement in my code, but please bear with me as this is my first venture into the CSS/HTML/Javascript realm.

Thank you very much for your time and assistance.

Answer №1

There are a variety of methods you could use for this task, depending on your specific needs. One option is to send an AJAX request to fetch the URL of an image and then update the src attribute of your image element with this new URL. However, it might be more efficient in this scenario to have both images already loaded in your HTML code and simply switch their visibility using JavaScript based on the 'w' state. This approach can provide a quicker response time for users.

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

Ways to postpone a for loop in Jquery

Currently, I am working on creating an image gallery using a for loop to load all the images. However, I am facing an issue where the loop is running too fast, and I would like to add a delay after each iteration. I attempted to use a timeout function, bu ...

Automatically Resizing an iFrame Height Upon Submit Button Click

Currently, I am facing an issue with a form that generates an iFrame for the Payment section. While the height of the iFrame is set correctly, whenever there are errors in the form submission and error messages appear, they push the submit button below t ...

Unusual css glitch observed when hovering over a span/link

Currently, I'm struggling with a CSS code issue. My goal is to have the div #hidden show when someone hovers over the link in #trigger. <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> ...

Error in React Native: The function this.setState is not defined. (The function "this.setState" is not a valid function)

I am working on integrating JSON data from an open source API and storing it as a state. However, I am facing challenges in saving the JSON data into the state which I want to use for city matching. It would be really helpful if someone could provide assis ...

muiSlider limited to specific range

I am currently using the Mui Slider component for a user interface where I need to restrict its value within a certain range. For example, I want the slider's handle to become unmovable after reaching 50. Users can still select values up to 50, but th ...

Troubleshooting: jQuery AJAX not Invoking C# Method in ASP.NET MVC Application

I am attempting to initiate a call to the controller from the views using jQuery ajax, however, it seems like the controller is not being called. The goal is to pass the token value obtained on the registration page to the controller in order to utilize it ...

Keep the footer at the bottom of the screen without needing to define a 100vh in Material UI

In the process of developing my react app with MUI framework, I encountered various challenges in creating a sticky footer at the bottom of my screen. After exploring different solutions, one approach that I found most satisfactory is as follows: export de ...

Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request Original query: I am utilizing the file_picker_callback type image I have enabled the image_description input field in my ...

Can property overloading be achieved?

Can functions be overloaded in the same way properties can? I'm interested in overloading properties to have separate documentation for different types passed to them. Currently, both values are set to the same value but I need distinct JSDoc for dif ...

Creating a responsive grid layout with HTML and CSS

Is there a way to adjust the grid layout so that the second row of blocks align just below the corresponding block above instead of creating an entirely new row? http://jsfiddle.net/AndyMP/wSvrN/ body { margin-left: 0px; margin-top: 0px; marg ...

Error encountered in NextJS: Trying to call res.unstable_revalidate which is not a function

I recently tried out a cutting-edge feature introduced in NextJS v.12.1 . The API itself is functioning correctly and can be accessed. However, I encountered a 500 error with the message res.unstable_revalidate is not a function. This issue persisted wheth ...

Using Javascript to extract elements from JSON objects

This is the output I receive after executing a script. { "log": { "entries": [{ "startedDateTime": "2020-12-01T08:45:30.123Z", "time": 50, "request": { "method": "GET", ...

How to maintain the previous position of Rzslider in Angular Js after selecting the date?

I am currently utilizing RZslider for date and time picking, but I am encountering repeated issues. As a newcomer to Rzlider and angularJs, I am struggling with some aspects. The slider is set to display the current time plus 4 hours and minus 4 hours. For ...

Ways to utilize two distinct XPATH values for a single key

When dealing with Xpath for the same object in two different portals, the paths can be: //*[@id="abc"]/fieldset/div/div/div[1]/label //*[@id="xyz"]/fieldset/div[1]/fieldset/div/div/div[1]/label In order to use both values in the same key and have Seleni ...

How can I troubleshoot the issue of not receiving a response while attempting to upload an image using Postman with my Cloudinary-Express API?

Currently developing a backend nodejs/express API to upload image files to Cloudinary, encountering an error during testing with Postman. Below is the backend code: app.post( '/api/upload/:id', asyncHandler(async (req, res) => { try { ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

Tips for incorporating unique images into each individual flex box

I am new to the world of coding, having just embarked on this journey less than a week ago. Following a tutorial by a developer on YouTube, I tried to add my own twist to the project in order to differentiate it from the original. However, I've hit a ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

Creating an interactive login form with jQuery and AJAX

I'm currently working on a website where I have placed a login box in the top right corner. My goal is to allow users to log in without refreshing the page. Although I've managed to get the initial login process working, I am facing challenges w ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...