Updating the variables of HTML components using JavaScript after making an AJAX request

I am using ajax to fetch a list of user data. But after this ajax call, I need to display the data in an HTML structure like a datasheet for each user. My question is how can I store the HTML code in a functional and elegant way to maintain readability and easily insert the user's data.

Is creating a separate file with the component template and including it through javascript the best approach? If so, how can I achieve this? If not, what would be the best alternative?

What I currently have:

Ajax call:

$("#list-users").click(function(ev){
    ev.preventDefault();
    $.ajax({
        url     : '/ajax/Users.php',
        type    : 'POST',
        dataType: 'json',
        data    : data,
        success : function(users){
            users.forEach((user, index) => {
                //The issue lies here. I am searching for a method to
                //store the HTML component code without needing to embed
                //the code inside a variable.
                var complexHtml = '...<p>' + user.name + '</p>...';
                $('.list').append(complexHtml);
            })
        }
    })
})

Answer №1

because having a large and unreadable success function.

... is this what you are searching for? `

let myUsersList = {};
let usersLoaded = false;

$("#list-users").click(function(event){
    event.preventDefault();
    $.ajax({
      url     : '/ajax/Users.php',
      type    : 'POST',
      dataType: 'json',
      data    : data,
      success : handleUserFunction 
    })
})

//...

function handleUserFunction(users) {
  users.forEach((user, index) => {

    let complexHtml = '...<p>' + user.name + '</p>...';
    $('.list').append(complexHtml);
})

`

Answer №2

Utilizing Vue/React/Angular can provide a straightforward solution as they handle the rendering process automatically. If you choose not to use these frameworks, here is an alternative approach I typically take:

  1. Create an HTML template structure and style it as invisible
  2. Use jQuery's clone method to duplicate the template
  3. Utilize jQuery to populate the template with data
  4. Use jQuery's appendTo method to display the template

Here is an example code snippet:

<div id="target"></div>

<div class="template-code" style="display:none">
    <div class="container">
       <div class="cls1"></div>
       <div class="cls2"></div>
    </div>
</div>

<script>
.... ajax success function (){
    var div = $(".template-code .container").clone();
    $(div).find(".cls1").html("data from ajax result");
    $(div).find(".cls2").html("data from ajax result");
    .... bind event as well if required ...
    $("#target").empty();
    $(div).appendTo("#target");

}
</script>

I hope this explanation proves to be beneficial.

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

What is the best way to combine TypedArrays in JavaScript?

Looking to combine multiple arraybuffers into a Blob, but facing limitations with TypedArrays that lack handy methods like "push". For example: var x = new Int8Array( [ 1, 2, 3 ] ); var y = new Int8Array( [ 4, 5, 6 ] ); The desired outcome is to have [ ...

extracting and interpreting JSON information from a socket using Node.js

Looking for a solution to buffer JSON data received from client(s) on my node.js net tcp server until the entire block arrives. I'm considering either parsing it or forwarding it elsewhere. Are there any modules out there that are compatible with the ...

What is the best way to exclude a field from a Joi schema?

I've defined a Joi schema for a User with the following rules: const userRules = Joi.object({ name: Joi.string().pattern(new RegExp('^[A-Za-zÁÉÍÓÚáéíóúãõÃÕâêôÂÊÔ ]+$')).required(), email: Joi.string().email().requ ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

The Node express GET route experiences intermittent failures when using wildcard match for every other request

I have configured my router to accept any GET request that does not include the word "API" in it. This is specifically for my single page application to handle bookmarked URLs that are not recognized by the app's routes. However, I am encountering an ...

Navigating through cards in HTML: A guide to filtering techniques

I'm currently in the process of developing a platform that enables users to browse through different profiles based on their first names. I've attempted to utilize bootstrap's "data-title" for searching purposes, but unfortunately, it's ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...

Is Q.js capable of functioning independently from node.js and require()?

Currently experimenting with the latest version of q.js to integrate promises into my ajax calls without utilizing node.js at all. I retrieved the most recent version from https://github.com/kriskowal/q and only included q.js in my project. While testing, ...

What is the method for extracting information from a dropdown menu using AJAX and transmitting it to a PHP script?

Looking to obtain the name of the selected category from a drop-down list using AJAX and send it to the PHP page containing the AJAX script. Here is the updated code: Action code: public function actionCreate() { $model=new News; // ...

Encountered an error when attempting to extend the array function: Uncaught TypeError - Object [object Array] does not contain a 'max' method

Hello, I am currently attempting to integrate this function into my code: Array.getMaximum = function (array) { return Math.max.apply(Math, array); }; Array.getMinimum = function (array) { return Math.min.apply(Math, array); }; This is inspired ...

The Discord.js error message popped up, stating that it was unable to access the property 'then' since it was undefined

I'm currently working on implementing a mute command for my discord bot, but I'm encountering an error that says; TypeError: Cannot read property 'then' of undefined I am unsure of what is causing this issue and would greatly apprecia ...

The validation process fails when the button is clicked for the second time

When adding a username and email to the userlist, I am able to validate the email on initial page load. However, if I try to enter an invalid email for the second time and click the add button, it does not work. <form id="myform"> <h2>Ad ...

There was an issue with rendering: "TypeError: Unable to access the 'name' property of an undefined object" [Vue alert]

I encountered the following error message: TypeError: Cannot read property 'name' of undefined Here's the snippet from the Vue file where the error occurred: <tr v-for="user in fields.data" :key="user.id"> <td>{{ user.id ...

Discovering what is impeding the rendering of a webpage

On a particular website, the server rendering happens quickly but there seems to be a delay on the client side which is causing the HTML to be rendered few seconds later. I suspect it could be due to some setTimeout function or similar; are there any tool ...

subscriptions to behavior subjects may not function properly across all components

When setting up my global service, I instantiate a BehaviorSubject variable dataWorkflowService: export class CallWorkflowService { url = 'http://localhost:3000/'; selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(&a ...

Ways to verify if a minimum of three letters in each variable correspond

let nameOne = 'chris|'; let nameTwo = 'christiana'; To use JavaScript, what is the best way to determine if three or more letters match between both variables? ...

Returning a Response in HapiJS Routes from Incoming Requests

Currently, I am facing an issue with the request module where I am able to successfully make a request and receive a response. However, I am struggling to figure out how to pass this response back to my route in order to return it to my client. Here is th ...

Determine the total hours and minutes elapsed between two specific dates and times

Looking for some assistance here. I have a form where users need to input a start time and end time of an incident. After entering this information, they would manually calculate the duration between the two date times. I am attempting to streamline this p ...

I am working on customizing my WordPress website using three.js to add a background with a wireframe effect. However, I am facing difficulties in placing a sphere at the end of each line

I have a beautiful turquoise diamond and I want to incorporate a directional camera view in the background of a WordPress section. However, I am unsure how to achieve this. The issue I'm facing is that I created a wireframe over the diamond, but when ...