Generate interactive HTML content and showcase JSON data within it

I am working on an AJAX API call that returns JSON format data. My goal is to display each value on the screen using HTML elements. Although I have achieved this, the design is not dynamic as needed. Additionally, I want to show a message ("No data available") if there is no data in the response. Below is a sample of my working HTML and JSON. To be displayed as shown below:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPPIYcw34/T38+jNPFUbAKIQFrVMFEb/c/RdPDFSPLb4Jm" crossorigin="anonymous"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
    <div class="portlet light bg-inverse tripcontainer">
        <div id="container">
            <!-- Driver Details Section -->
            <div class="col-md-4 driver">
                <div>
                    <label class="header">Driver Details</label>
                </div>
                <div>
                    <label>Name:</label>
                    <span class="dname"></span>
                </div>
                ... [additional lines representing dynamic HTML elements]
             </div>
        </div>
    </div>
</div>

Answer №1

It seems like you're looking to populate all the information provided, here is a way to achieve this using JavaScript:

var parsedData = JSON.parse(ajaxResponse);
if(parsedData.length == 0){
   console.log('No data available');
}else{
   var keys = Object.keys(parsedData[0]);
   
   for(var i = 0; i < keys.length ; i++){
      // Update elements with corresponding classes in HTML
      $("."+keys[i]).html(parsedData[0][keys[i]]);
   }
}

Your updated HTML structure should look like this:

<div>
   <label>Email:</label>
   <span class="email"></span>
</div>

Answer №2

When it comes to populating JSON data in HTML, there are various methods that can be used such as Ajax, getJSON, Fetch, JavaScript (pure), and XMLHttpRequest.

Below is an example showcasing the fetch() method. Feel free to customize it based on your specific requirements:

<div>
    <table>
        <tbody id="my-list">
            <tr>
                <th>Field 01</th>
                <th>Field 02</th>
                <th>Field 03</th>
                <th>Field 04</th>
                <th>Field 05</th>
            </tr>
        </tbody>
    </table>
</div>


<script>

$(function () {
    const url = 'https://jsonplaceholder.typicode.com/todos';
    fetch(url, { /* other parameters */ })
        .then(resp => resp.json())
        .then(data => { // Your code for handling the data you get from the API
            renderData(data);
        })
        .catch(function (error) { // This is where you run code if the server returns any errors
            console.log('There has been a problem with your fetch operation: ', error.message);
        });
});


function renderList(data) {
    var list = "";
    $.each(data, function (index) {
        href = "https://jsonplaceholder.typicode.com/todos?id=" + data[index].Id;
        list += "<tr>";
        list += "<td>" + data[index].Field01 + "</td>";
        list += "<td>" + data[index].Field02 + "</td>";
        list += "<td>" + data[index].Field03 + "</td>";
        list += "<td>" + data[index].Field04 + "</td>";
        list += "<td>" + data[index].Field05 + "</td>";
        list += "</tr>";
    })
    $("#my-list").append(list);
}

</script>

Hopefully, this information proves useful...

Answer №3

If you want to make this dynamic, here are the steps you can follow:

1. Set values for the driver like so:

$('.dname').html(driver_data[0].employeename);

2. Set values for the passenger like this:

$('.pname').html(driver_data[0].passenger_data[0].employeename);

3. Iterate through your results (This step should come first):

for (i = 0; i < result.length; i++) { 
// assign values here
}

In this example, I have parsed and added values.

Here is how it looks after the updates:

[![view image][2]][2]

Note :

  1. I have included some fields for both the driver and passenger, which you can customize as needed by iterating through them.

  2. Avoid creating static HTML, instead use jQuery to add elements dynamically, resulting in a cleaner code.

Update :

To address the OP's query about iterating through the result and adjusting the data, check out the updated fiddle that offers a dynamic iteration solution.

Here's how it appears:

[![Output][4]][4]

$(document).ready(function() {
    $.get("http://www.mocky.io/v2/5ba349e82f000054009685b0", function(data, status) {
        var output = '';
        for (i = 0; i < data.length; i++) {
            var driverHtml = '<div class="col-md-4 driver"><div><label class="header">Driver Details</label></div><div><label>Name:</label><span class="dname">' + data[i].employeename + '</span></div>';
            var passengerHtml = '<div class="col-md-8 passenger"><div><label class="header">Passenger Details</label></div><div><label>Name:</label><span class="pname">' + data[i].passenger_data[0].employeename + '</span></div><hr>';
            output += driverHtml + passengerHtml;
        }
        $('#container').html(output);
    });
});

Note for update :

I utilized Mocky for dummy Data to mimic the real-time output shown here.

The HTML is also constructed dynamically with only a few fields filled out. Feel free to populate the rest of the fields as necessary.

Hopefully, this guide proves helpful to you.

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

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...

Background in CSS ::after pseudo-element not showing up

I've been attempting to show a tick image after a div element, but no matter what CSS properties I try, I can't seem to get it right. Previous answers to similar questions haven't provided the solution I need. HTML: <div class="link-in ...

Unable to scroll within ion-view component

I recently started working with the ionic framework and I am currently struggling with a scrolling issue in my page design. Below is the code from my index.html file: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> & ...

Expand and Collapse Button for Customizing Table Height Individually

I trust everything is going smoothly. A challenge I'm facing involves implementing a button to expand a specific row within a table. Currently, clicking the "show more/show less" button extends all rows when the goal is to do it for each individual ta ...

Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below, .then((response) => { return response.json(); }) .then((jsonRespo ...

jQuery append allows for the addition of multiple items simultaneously

I need assistance with automatically creating a div when clicking on a button. I'm encountering an issue where each click increments the display of the div. Can you provide some guidance on how to resolve this problem? ...

Skipping code in JavaScript/jQuery function on window load

I have created a function that applies specific CSS rules to elements when the window is fully loaded. Check out my code below: function applyHover() { $('.view_preloader .overlay').css('opacity',1); $('.view_pre ...

Using AJAX and jQuery, the result is retrieved and inserted into a <div> element

Having trouble populating a DIV with the result of a simple GET request using AJAX and jQuery. What could be causing the issue? <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <scrip ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

Using Angular/Typescript to interact with HTML5 Input type Date on Firefox (FF)

Are there any Angular/Typescript projects that are completely built without relying on third-party libraries? I am encountering problems with Firefox and IE11. It works fine on Chrome where the value can be read, but the calendar does not display when us ...

When the label is clicked, retrieve the value of the checkbox within

I have a checkbox inside a label, and for design purposes, I added a div there. My requirement is to get the checkbox value on the click event of the label. However, I am always getting false whenever the checkbox is clicked. <label class="text-xs col- ...

my AJAX code isn't redirecting me to the desired URL in the background

I am seeking to utilize ajax for navigating to a php script in the background in order to execute certain commands. However, I'm encountering an issue where the commands are not being executed. This leads me to believe that there may be an error in my ...

Unresponsive Button_tag within a Rails table

The situation is as follows: I have a button_tag located within a form that is nested inside a table: <div class="table-responsive tableBG"> ** Interestingly, the button functions perfectly when placed here ** <table class="table table-striped ...

Searching for an element with a changing name using jQuery - Struggling with quotes

Looking to navigate my DOM based on the value of an option in a select box. The value of "searchkey" can vary based on user input, for example: searchkey = dell'anno searcheky = dell"anno These options, particularly the first one, can cause issues ...

Display JSON data retrieved from PHP script on Windows Phone 8.1 platform

After running a PHP file, I receive the following JSON data: {"Name":"Waqas","Age":37,"Address":"Kanju"} Interestingly, when I try to execute the same method on Windows Phone, I get the exact same JSON output: {"Name":"Waqas","Age":37,"Address":"Kanju"} ...

What causes discrepancies between jQuery set attributes and .html() output?

In an attempt to set attributes on HTML snippets, I am aiming to repopulate a form with previously entered values. Despite using .attr() to set the attributes, they do not appear after using .html(). For reference, I have provided a simple example here: h ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

Retrieve all information from a JSON array

Encountering a minor issue with a basic task. Here is the code snippet in question: JavaScript code Currently able to access the first object element, however, I require all the data objects. I suspect that a modification is needed in this particular cod ...

Error message 'Object doesn't have support for this property or method' is triggered by a basic JSON object

Recently, I developed a compact framework for loading resources asynchronously (hyperlink). The framework functions properly in modern browsers such as Opera, Chrome, and Firefox. However, when testing it in IE8, the code fails to execute. Internet Explor ...

What is the best approach to decode this JSON object in Swift 3.0?

Currently, I am in the process of parsing a JSON string that is being returned from an API. The format of the JSON string that I am working with is shown below. QuerySearchResult":{ "StartAt":"1", "Count":"40", "TotalAvailable":"500", "Items":[ {"TITL ...