Learn the process of applying distinct CSS classes to various elements within an AJAX response

The client initiates an AJAX call via jQuery. Upon fetching data from the database, I return the response which includes the application of numerous classes and styles to various HTML tags. Unfortunately, this process results in code that appears unsightly.

while (my @data = $statement->fetchrow_array())
{
    print "<li class='productWrap $data[7]' style='height:200px; width:150px;'>
            <center> 
                <div class=\"productImageWrap\" id=\"productImageWrapID_$data[0]\">
                    <img src=$data[5] width='75' height='75'' />
                </div>
                <div>
                    <div style='font-size: 11px; font-family: \"Verdana\"; '> $data[6] $data[1] $data[2] </div>
                    <b>                             
                        <span> <strike> $data[3] </strike> $data[4] </span>
                        <a href='#' id=\"featuredProduct_$data[0]\" onclick=\"adjust_menu(this.id); simpleCart.add('name=$data[6] $data[1] $data[2]', 'price=$data[4]','image=$data[5]'); return false;\">   
                            <img src='images/add-to-basket2.gif' alt='Add To Basket' width='111' height='32' id='featuredProduct+$data[0]' />
                        </a>
                    </b>

                </div>
            </center>
        </li>";
}

Is there a way to avoid this cumbersome process? Perhaps applying the classes and styles on the client side after receiving the response could be a better solution.

Answer №1

A great method is to store information in a JSON string, send it to the client, and allow it to display the outcomes.

There are multiple jquery template tools available. One intriguing choice is as follows:

<script type="text/template" id="itemTemplate">
    <ul>
        <li class='productWrap' style='height:200px; width:150px;'>
            ...
       </li>
    </ul>
</script>

Because this isn't written in JavaScript, the browser won't interpret or render it. Nonetheless, you can employ jQuery $('#itemTemplate ul li') to access the list item. Subsequently, utilize jQuery techniques to inject the data into the template and implement CSS styles, etc:

var item = $('#itemTemplate ul li');
item.addClass(data[7]);

Further resources:

  • Latest jQuery templates for 2012?

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

When clicking on the file input field in Angular.js, the image name mysteriously disappears

I am currently utilizing ng-file-upload to upload images with Angular.js. The issue I'm encountering is that when a user selects a file for the second time in the same field, the name of the previously chosen image doesn't display. Below is my c ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Does expressJS use the express() function as a global function?

Can anyone confirm if the express() function used in the second statement is a global function? I have searched my project folder but couldn't find its declaration. var express = require('express'); var app = express(); var fs = require("fs ...

Jquery failing to function properly when scrolling

I have been attempting to implement a feature where an element changes its position to fixed after scrolling past a certain point. However, no change occurs when I scroll. In the <head> section of my code, I have included <script src="stiler/jquer ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

What is the best way to organize and group messages in JavaScript in order to push them to a subarray?

Having trouble coming up with a name for this question, but here's the issue I'm facing: I currently have an array in PHP containing several entries. Array ( [0] => stdClass Object ( [sender_id] => 0 [me ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

Creating a jQuery alertbox that is triggered by specific elements in an anchor tag

I am working on an HTML page that contains 50 A tags. I am trying to figure out how to create an alert based on a specific element inside the A tag. Here is an example of what I am looking for: <a href "something">click to see the alert</a> ...

How come Selenium is stopping me from extracting text content from the "ul" and "li" elements?

This piece of code represents my work: from selenium import webdriver from selenium.webdriver.common.keys import Keys # For being able to input key presses import time ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

Issue with event firing is occurring following closure of Foundation reveal

On my webpage, I have implemented a button that triggers the opening of a modal using jQuery and Foundation. Here is an example of how it appears in the code: $(".playersScores").unbind('click').bind('click', function () { $(' ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Sorting a dynamic menu to assign custom classes with PHP

<?php // Select all entries from the menu table $sql1 = $pardConfig->prepare("SELECT id, menu_title, menu_link, parent FROM pard_menu ORDER BY parent, sort, menu_title"); // Create a multidimensional array to conatin a list of items and parents $sql1 ...

Content submission and updates, modeled after the Twitter platform

Hello there. I am currently working on a quotation service and ran into an issue while attempting to implement twitter-like data submission and display: all of my ajax requests seem to be executed twice. I am using jQuery in the following manner: I hav ...