Learn how to generate a table directly from code instead of relying on a .json file

I need help modifying this code snippet that currently reads JSON data from a file. I have generated the JSON data from my database and would like to update the code to read it directly instead of from a file. You can refer to how the JSON is being accessed in this example. In my code snippet, you will see how the data is retrieved to populate the table.

var columns = ["username", "user_id", "address", "state", "postal_code", "phone", "email"];

var level_classes = {
    "NEW": "new_client",
    "RENEWAL": "renewing_client",
    "CURRENT": "current_client"
};

$(document).ready(function() {
    $.getJSON("obtainUsers.php", function(data) {
        var $table = $('<table style="width: 100%;">');
        var $tbody = $('<tbody>');
        $table.append($tbody);
        var $tr = null;

        data.forEach(function(user, index) {
            if (index % 4 === 0) {
                $tr = $('<tr>');
                $tbody.append($tr);
            }
            $td = $('<td class="' + level_classes[user.level] + '">');
            columns.forEach(function(col) {
                $td.append(user[col]);
                $td.append($('<br>'));
            });
            $tr.append($td);
        });
        $('.runninglist').append($table);
    });
});

I appreciate any guidance. Thank you!

Answer №1

If you want to dynamically load content onto your webpage using jQuery, you can use the following code:

$(document).ready(function() {
    $(".TableWithClass").each(function(){
        var ThisTableHere = $(this);
        $.getJSON($(this).data("url"), function(data) {
            var $table = ThisTableHere;
            .
            .
            Use your other data parameters here
            .
            .
            $('.runninglist').append($table);
    });
});

The key difference with this approach is that the client will have to wait for the page to fully execute before getting the complete HTML content. In contrast, if you use an ajax call in another method, your page will load first and then make a request to fetch additional data asynchronously.

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

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

The function '.save' is not recognized by Mongoose

As a newcomer, I have been trying to understand the code in this calendar app that I created using express-generator. Everything seems to be working fine with connecting to MongoDB, but I am facing issues when trying to save a document. The section of my ...

Executing a serverless function in Next.js using getStaticPaths: A step-by-step guide

In my current project, I am utilizing Next.js and the Vercel deployment workflow. To set up page generation at build time, I have been following a guide that demonstrates how to generate pages based on an external API's response. // At build time, t ...

"Encountered an issue while attempting to send the message: Unable to retrieve data" while utilizing NextJS and the

Currently, I am utilizing fetch along with NextJS to attempt to send information such as name, phone number, email, company, and message to an API. However, I am encountering an issue where the error message simply states 'Failed to fetch' in the ...

Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory: var szGetData = "some url that works"; myApp.factory('Data', function ($http) { var eventData = {}; eve ...

Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment: <package id="jQuery" version="3.2.1" targetFramework="net45" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> Recently, I encountered an issue while trying to send a request from one ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

Integrating node.js into my HTML page

Forgive me for sounding like a newbie, but is there a simple way to integrate node.js into my HTML or perhaps include a Google API library? For example: <script>google.load(xxxx)</script> **or** <script src="xxxx"></script> ...

obtainServerSideProps query parameter

Hey there, I'm trying to use NextJS and its getServerSideProps function to send an API Request, but I'm having trouble passing my ID Query Parameter along. The URL for my API is: http://localhost:3001/product/${id} Below is my code: const rout ...

Do watches operate asynchronously?

I am monitoring the status of a variable called radioStatus within a Vue instance: watch: { radioStatus: function(val) { if (!this.discovery) { $.ajax({ url: '/switch/api/radio/' + (val ? 'on' : 'off') }) ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

How can I access the data variables from a JSON request within a function?

My task involves loading multiple JSON files from an array called bunchOfData, with each file having a corresponding URL. How can I access my variable "myI" within the processData function? for(var i = 0; i < bunchOfData.length; i++){ $.getJS ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Unable to view mobile version on HTML page / lack of responsiveness observed

<body> <nav class="navbar navbar transparent"> <div class="container-fluid logo"> <div class="navbar-header"> <a class="navbar-brand" href="#"> <img src="images/Logo.png" /> & ...

What is the best way to add a CSS rule to JavaScript?

animation: scaleUp 0.3s linear 0.4s forwards; animation: scaleDown 0.3s linear forwards; Greetings! I'm currently working on adding animations to my content filtering functionality. Specifically, I want to incorporate the aforementioned CSS rules in ...