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

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

Unable to establish a connection with the websocket server

I set up a websocket server on my host at <www.example.com>, but for some reason, the client is unable to connect to it. Here is the code : Server.js : const ws = new require('ws'); const wss = new ws.Server({noServer: true}); const htt ...

Utilizing JSON data to populate a modal window in HTML

How can I incorporate JSON data into an HTML modal window? I have a set of 12 buttons, and when a user clicks on one, I want to display the corresponding month's information from a JSON file. let myJson; $(`button`).on(`click`, function() { let ...

The jQuery date picker refuses to function correctly when I attempt to initialize it after an AJAX call

I am facing an issue with my jquery-ui datepicker not working within the document.ready function after making an ajax call. However, it works fine when I add it inside the ajax complete function. Can someone please provide assistance on what could be cau ...

The process of refreshing a TableView using JSON data

I'm facing a challenge with updating data on my website from JSON. I have a TableView that retrieves data from a JSON URL. When I click the button, the information from JSON is displayed in the tableviewCell, but I want this information to update auto ...

Having trouble with opening and closing popup windows in JavaScript while using Android frames?

To display additional information for the user, I create a new tab using the following code: window.open("/Home/Agreement", "_blank"); Within the Agreement View, there is a button with JavaScript that allows the user to close the Popup and return to the m ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

Converting jQuery DataTables into CSV Format: A Quick Guide

Currently, I am utilizing jQuery datatables in my project. I am looking for a method to easily convert these datatables into CSV format. The data is being retrieved as JSON objects. Any help or guidance on how to accomplish this would be greatly apprecia ...

How to Use RestKit on iOS to Retrieve a Specified Number of Elements Instead of the Entire

I am looking to implement an app similar to Twitter where objects are loaded in tens from the JSON data instead of loading all at once. Is there a way, using RestKit, for the "load more" button in UITableView to load the next ten objects if they exist in t ...

Designing a Bootstrap table using various Angular elements

I'm currently in the process of developing a Bootstrap table that utilizes two Angular components. This is how my code is structured : componentA.html <table class="table table-bordered"> <thead> <tr> <th scope="col">#</ ...

What is the best way to include a character in a string if there are no instances of the same character already present?

Looking for help with a function that can determine if a string contains a period and add one if it doesn't. So far, I'm struggling to make it either continuously add periods or not add any at all. function checkPeriod() { if (inputString.indexO ...

What is the best way to refrain from utilizing the && logical operator within the mapStateToProps function in Redux?

When I'm trying to access a nested state in a selector, I often find myself having to use the && logical operators. const mapStateToProps = store => ({ image: store.auth.user && store.auth.user.photoURL; }); If I don't use ...

transmit a JSON string to the server using the POST method

I have tested multiple examples sourced from various places but unfortunately, none of them seem to work for me. Every attempt results in an error or a null object on the server side. Below is the client-side code snippet: jsonManual = JSON.stringify(x); ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

Dynamically shift the table footer to the bottom of a scrolling div by utilizing jQuery

I'm facing a challenge where I need to relocate each th tag from the footer row of a table to the bottom of a scrolling div. You can check out the scenario on this link. Currently, I am able to achieve this by hardcoding it like so: $('.sticky- ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

Is it possible for an ASP.NET web service to unexpectedly terminate due to the presence of "&" in

I have a mobile application for iPhones that communicates with an asp.net webservice using JSON. Everything works smoothly with all the data, but whenever I include an "&" symbol in any data field, it triggers a server error as shown below System.Argumen ...