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

Moving a component beyond its container using a query

After much searching, I have yet to find a solution to fix this issue. My problem involves having a list with draggable elements within a scrollable area. The goal is to drag these elements outside of the parent div into a droppable area; however, they see ...

What are the placeholders for the "localIdentName" query tag in a custom CSS-loader for Webpack?

Just starting out with Webpack and experimenting with the css-loader. I came across the option to specify a localIdentName query tag on the Github page under "Local Scope". This tag allows us to define our own custom values for how classes should be named ...

Unknown Tag in AjaxControlToolkit's HTML Editor Component

I am trying to incorporate an HTML editor into my code. Here is the snippet I have: <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> ...

Leverage the power of jQuery and AJAX in conjunction with the Laravel framework to showcase and

I am currently working on a page that showcases various products. Initially, I had set up a route as follows: Route::get('products/{category}/{subcategory}') In my controller, I was returning results from the database to display the items. Howe ...

Tips for displaying the HTML content within the autocomplete box

My situation involves a text input and an HTML form where users can submit their name to retrieve information. I am using AJAX to display the usernames dynamically. <div class="hidesearch" id="search" style="width:"400px;"> <inp ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

Is it possible to initiate validation on an HTML element without the presence of a form?

Is it possible to trigger validation on an HTML element without using a form? For example, I have set the required attribute on a field, but when I click the Save button, the field doesn't display the red outline indicating validation failure. I susp ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

Automatically advance to the next input field and go back when the backspace key is pressed after reaching the maximum length

Creating a credit card input field that switches cursor after reaching maximum number length and focuses on previous field when deleting with backspace. (function ($) { $(".nmipay-input-field").keyup(function () { if (this.value.l ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Implementing a delete functionality within a loop on a JavaScript object array

I have a JavaScript object with the following structure: var partner = { p_name: { value: partner_name, label: "Name" }, p_id: { value: partner_ID, label: "ID" }, p_status: { value: partner_status, label: "Status" }, p_email: { value: partner_emai ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

What is the speed of retrieving new data once it has been inserted into a firebase real-time database?

In the midst of developing my personal project using next.js, I've encountered an issue with a component that includes a getstaticprops function. This function scrapes a website and then posts the extracted data to a firebase realtime database. Howeve ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...

I'm curious if it is possible to retrieve the dates of actions on websites using Selenium with Python

Is there a way to retrieve the date of data, like the date of comments, using HTML codes? I need assistance on how to achieve this through selenium in Python. Can Jquery be used as a solution? ...

Selecting multiple items in jQuery based on different attributes is a useful feature that

I am looking to choose multiple items based on their data attribute. Each item has a unique data-id. <div class="foo" data-id="1"></div> <div class="foo" data-id="2"></div> <div class=" ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...