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

Is the direct checkout link specifically designed for use on individual product pages?

Currently, I am working on enhancing a WooCommerce website by enabling Ajax across all pages. As part of this optimization, I have introduced a custom Direct Checkout button to the checkout form. However, there seems to be an issue with the functionality o ...

What is the best way to create spacing between images in a CSS image slider?

UPDATE: I've made significant progress by modifying the code provided in the link below. I am very close to achieving my desired result, but there are parts of it that still puzzle me. The transition now has spacing on both sides and the hidden space ...

Showing a confirmation message to the user upon clicking outside of a specific section

On my webpage, I have a section for creating content, as well as a top bar and sidebar with internal links (both controlled by ng controllers). I am looking to implement a confirmation message that will appear if the user tries to leave the page while in t ...

Turn off padding in material ui card

Currently, I am utilizing a material UI card and upon inspecting the card, I noticed the presence of this unique class: "MulticardContent-root". This class adds padding of 16 which I would like to remove. Strangely, it is not located within the styles co ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

What is the best way to transfer a value to the database using a distinct module?

I have recently set up a basic express project and added a file named lib/userhandler.js in the main directory. //lib/userhandler.js exports.addUser = function(req, res){ // Accessing our internal database variable var db = req.db; // Retrieving ...

Having trouble with my Express.js logout route not redirecting, how can I troubleshoot and resolve it?

The issue with the logout route not working persists even when attempting to use another route, as it fails to render or redirect to that specific route. However, the console.log("am clicked"); function works perfectly fine. const express = require('e ...

React Native's state changes dynamically, however, the JSX conditional rendering fails to update the user interface accordingly

Greetings and thank you in advance for your time! I'm currently facing a unique challenge with React where I am struggling to render a specific UI element based on a check function. My goal is to create a multiple selection filter menu, where clickin ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Alter the appearance of an alert message to appear on the screen using jQuery

Looking for some help with my calculator project. I'm trying to figure out how to display a number when it's clicked on, but all I can manage so far is an alert popping up. Here's the current code snippet: var add = function (x,y){ retu ...

What is the best way to retrieve data from the next page in a Protractor test?

I am currently in the process of automating the test for booking a flight. When I enter the credentials on the homepage, click the Submit button, and the browser navigates to the search results page. const EC = protractor.ExpectedConditions; describe( ...

What steps can I take to ensure that my keyup function is not delayed by one character?

Whenever I type something in my textarea, I want the text to instantly display in my result box. I've tried using both the keyup and keydown functions, but I'm facing an issue where there is a delay of one character when typing quickly. For exa ...

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Tips on retrieving the text content of an HTML element using its tag

Is there a way to retrieve the selected text along with its HTML tags using window.getSelection()? When using window.getSelection(), it only returns plain text such as HELLO. However, I need the text with the HTML tag included, like this <b>Hello< ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...