Switching the background color of a <td> based on an array provided in the AJAX response

My goal is to dynamically change the background-color of elements based on values in an array. However, I am facing a problem where all elements are displaying with the same color instead of changing according to the value.

I have attempted using jQuery with AJAX to achieve this, but despite console messages indicating success, the result on my site does not match. I really could use some guidance here.

The code snippet below shows one of my AJAX functions. It is supposed to display 1 green element and 4 brown/red ones. Yet, I keep seeing either all red or all green elements.

Here is the array I receive:

[1776220,17 ,242332 ,1119098, 500633]


function listThem() {
  let color = '';
  $.ajax({
    type: "GET",
    url: "php/vehiculos/testServicio.php",
    data: "data",
    success: function(response) {
      let dynamicData = JSON.parse(response);
      // DYNAMIC SERVICE VARIABLE
      // Resetting here
      $.each(dynamicData, function(i, elem) {
        if (dynamicData[i] <= 86400) {
          console.log(elem);
          color = '#51d847';
        }
        if ((dynamicData[i] > 86400) && (dynamicData[i] < 172800)) {
          console.log(elem);
          color = '#F18D05';
        }
        if (dynamicData[i] >= 172800) {
          console.log(elem);
          color = '#E54028';
        }
      });
    }
  });
}

$.ajax({
  url: 'php/vehiculos/listing.php',
  type: 'GET',
  success: function(response) {
    /** Convert response into usable object */
    let dataList = JSON.parse(response);
    
    let template = '';
    dataList.forEach(vehicle => {
      template += `<tr taskId=${vehicle.posId}>
         <td class=''>
             <a>${vehicle.name}</a>
         </td>
         <td style='background-color:${color}';>
             ${vehicle.ultimaUpdate}  
         </td>
         <td>${vehicle.phone}</td>
         <td>${vehicle.category}</td>
        </tr>`
      $('#registros').html(template);
    });
  }
})

Answer №1

Make sure to utilize the .append() function instead of .html() within your loop. This will prevent you from overriding the existing content.

$('#registros').append(template);

Additionally, I have included else-if statements and the && operator for added functionality.

function listThem() {
  let color = '';
  $.ajax({
    type: "GET",
    url: "php/vehiculos/testServicio.php",
    data: "data",
    success: function(response) {
      let dinamica = JSON.parse(response);
      // VARIABLE FOR DYNAMIC COMMUNITY SERVICE
      // Here we are attempting to reset
      $.each(dinamica, function(i, elem) {
        if (dinamica[i] <= 86400) {
          console.log(elem);
          color = '#51d847';
        }
        else if ((dinamica[i] > 86400) && (dinamica[i] < 172800)) {
          console.log(elem);
          color = '#F18D05';
        }
        else if (dinamica[i] >= 172800) {
          console.log(elem);
          color = '#E54028';
        }
      });
    }
  });
}

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

My jquery filter is not functioning properly

I need help making the active class work on each category when clicked, shifting to the next one. I've tried implementing it but no luck so far. $(document).ready(function() { $('.list-inline-item').click(function() { const value = ...

"Update content dynamically with PHP-AJAX only when there are

Hey there, I've got a comment system that's being constantly updated with jQuery. My goal is to only refresh it when new records are added to the database. Is this possible? Please forgive any mistakes in my English, as I'm using Google Tra ...

Modifying the content inside a div element and inserting an image into it

I am facing a problem where I am unable to display the image when trying to change the inner HTML of a div by inserting an img source into it. Below is my JavaScript code snippet: var sliderimg = document.getElementById('abc_'+obj).src; $("#eve ...

Having trouble with Ajax functionality on the portlet configuration JSP page in Liferay 6.2?

Currently developing a MVCPortlet (Liferay 6.2). Curious about why this ajax call functions as expected on a standard jsp within my portlet, but fails to work on the configuration page of the portlet (the jsp that appears when you click on the top right c ...

Exploring the power of DOM manipulation in both jQuery UI and AngularJS UI Router

I have a query regarding the integration of jQuery UI and AngularJS UI Router. My aim is to incorporate jQuery UI themes into my application, however, when using AngularJS UI Router, I face issues with an incomplete DOM tree. Is there a way to successfull ...

What is the best method for seamlessly loading JSON data while transitioning between pages in a jqtouch application?

I've been working with JQTouch for my application. While the demos showed how to retrieve an html file and display it in the user interface, I'm dealing with loading JSON data that I want to incorporate into an existing DIV element. I prefer not ...

Encountering an issue with displaying data fetched from omdbapi, receiving [object Object] instead

Everything is working perfectly in my code except for the mysterious appearance of [object Object] whenever I perform a search. I've combed through my code multiple times, but I just can't seem to locate the source of this issue. It would be grea ...

Tips on adjusting the size of a Materialize CSS datepicker to perfectly fit within a card

Currently, I am developing a login page in html utilizing the materialize css framework. In my design, I created a card where Login and Register are displayed as tabs within the card. However, one of the forms includes a datepicker from materialize which ...

Populating a dropdown list with options

When selecting a value from the first dropdown list, a MySQL query is used to return data which should populate the second dropdown list. However, there seems to be an issue with the second list not getting populated, even though the code appears to work f ...

Using jQuery to dynamically retrieve a radio button

After struggling with this issue for quite some time, I have come to the realization that it's too complex for me to handle on my own. I could really use some assistance here. The problem at hand involves a page displaying various products, each of w ...

"Exploring the best method to send an AJAX callback to a particular div that has been dynamically generated using

Exploring a specific scenario: Below you'll find some HTML code representing rating stars generated through a PHP foreach loop. Each div with the class rating has a unique $file_id value. <div class="rating" data-rating="<?php echo $round;?> ...

Looking to display a submenu next to its parent element

I have a list that is not in order: <ul> <li>Parent-1 <ul> <li>Child-1</li> <li>Child-2</li> <li>Child-3</li> </ul> </li> <li>Parent-2 <ul> <li>Ch ...

"Utilize JQuery to insert data into the database seamlessly, without the need to refresh the page, allowing for

I am currently using jQuery and PHP to retrieve data from a table and then insert it into a database. However, while the insertion without refreshing the page using jQuery is successful, it ends up inserting the last fetched row multiple times. Here is m ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

Animating with jQuery to a specific offset or position

Currently, I am utilizing jQuery animate to modify the location of an element: $('#item').animate({'top' : '-50'}, 0); The goal is to set the position without any animations. I experimented with both offset and position, but ...

Reset all divs to their default state except for the one that is currently active using jQuery

Here's the plan for my script: Once a user clicks on a "learn more" button, it will reveal the relevant information in the corresponding box. I'm aiming to implement a feature where if you click on another "learn more" button while one box is a ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Making an AJAX request in Javascript to retrieve multiple values using the HTTP method 'GET' from a URL

xmlhttp.open("POST","BAConsultRecordsAJAX.php?q="+str,true); Could this be achieved? xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str+"j="+str2,true); I need to have values stored in both q and j fields. ...

Restricting Textarea Search in jQuery DataTables

I'm encountering an issue with a table field that can contain up to 63000 characters. I'm using jQuery datatables for filtering by keywords, but it seems to only pick up the first few characters within this field. Even with a large textarea of ch ...

Conceal a div containing certain content using jQuery

Can you use jquery to hide a div with the class "one" if it contains the following content? <div class="one"> <div style="padding:20px;"> <div class="title"></div> <div class="content"></div> < ...