Generating links within a Json file

Excuse me if this is a basic inquiry that has already been addressed, but I am not very familiar with javascript.

I want to design a json catalog that will be displayed as a table on an HTML page. I specifically need one of the cells to contain a hyperlink, but I am struggling to make it work.

Here is my json script:

"beer": [{
    "name": "NAME",
    "type": "TYPE",
    "company": "BREWERY",
    "website": "WWW.SITE.COM",
    "price": 6.00
}],

And here is my HTML script:

<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest()}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","catalog.json",false);
xmlhttp.send();
json=JSON.parse(xmlhttp.responseText);

document.write("<table class=table table-bordered>");
var x=json.beer;
for (i=0;i<x.length;i++)
{ 
document.write("<tr><td>");
document.write(x[i].name);
document.write("</td><td>");
document.write(x[i].type);
document.write("</td><td>");
document.write(x[i].company);
document.write("</td><td>");
document.write(x[i].website);
document.write("</td><td>$");
document.write(x[i].price.toFixed(2));                                    
document.write("</td></tr>");
 }
document.write("</table>");
</script>

If anyone can assist with this issue, I would greatly appreciate it.

Answer №1

First and foremost, it is strongly advised to avoid using document.write. If this function is invoked after the page has finished loading, it will completely overwrite the entire content. It is much more advisable to utilize DOM methods for adding new elements dynamically.

Additionally, since AJAX is meant to be asynchronous, there seems to be no apparent reason for passing in false to the .open() method. Moreover, considering the outdated versions of Internet Explorer are unlikely to access the site, the use of new ActiveXObject can probably be omitted as well.

// As of 2014, the following code suffices
var xhr = new XMLHttpRequest;

// Define the callback function upon request completion
xhr.onload = function(){
    // Checking if readyState is 4 (request complete) and status is 200 (HTTP OK)
    if(xhr.readyState === 4 && xhr.status === 200){
        var json = JSON.parse(xhr.responseText),
            x = json.beer,
            table = document.createElement('table');

        // Assigning relevant classes
        table.className = "table table-bordered";

        // Iterating over the data
        for(var i = 0; i < x.length; i++){
            // Constructing HTML for each row
            var row = '<tr>' +
                '<td>'+x[i].name+'</td>' +
                '<td>'+x[i].type+'</td>' +
                '<td>'+x[i].company+'</td>' +
                '<td><a href="'+x[i].website+'">'+x[i].website+'</a></td>' +
                '<td>'+x[i].price.toFixed(2)+'</td>'+
            '</tr>';

            // Appending each row to the table's innerHTML
            table.innerHTML += row;
        }

        // Adding the generated table to the page
        document.body.appendChild(table);
    }
};

// By default, the request is asynchronous
xhr.open("GET","catalog.json");

// Initiating the request
xhr.send();

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

How can you retrieve a value from a loop in JavaScript?

I encountered an issue while working on a function that deletes indexes not meeting the required "levels" in my database and then returns the updated array. Upon calling cleanWinners(winners, guild).then(res => console.log(res)), I noticed that it retu ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

Lens Flare Troubles in Three JS

I'm having trouble implementing the LensFlare Effect from the three js docs in react three fiber. I've tried using the code provided but it's not working for me. Here's what I have: import { extend, useLoader } from "@react-three/f ...

What is the process for including an SVG file in my JavaScript .textContent?

I've been struggling to add an exclamation SVG to this section, but for some reason I can't make it work. I've searched on Google for a solution, but haven't found one yet. The SVG file is already downloaded and stored in my project fo ...

Converting a CSV file to JSON in C++: A step-by-step guide

Are there any standard frameworks or efficient methods available for converting CSV fields to JSON format? The current process of converting the fields to an array and then converting to JSON is very slow. I am looking for faster alternatives, so please ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

Using JavaScript, create a script that will automatically convert the value of an AJAX calendar to a datetime

I am struggling with converting a string into a proper date format using JavaScript in an ASP.net textbox with AJAX calendar extender control. <asp:TextBox ID="tbxReceivedDate" CssClass="selectstyle" runat="server" MaxLength="100" Width="200" onblur="p ...

Rebooting checkbox data with AJAX on MVC 5 form submission

Within my application, I am utilizing an AJAX BeginForm: @using (Ajax.BeginForm("DeletePages", "Home", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccessDelete", OnFailure = "OnFailureDelete" }, new { id = "ToolBarActionsForm" })) { @Html.A ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

Using Angular to dynamically display JSON data on an HTML page

I have JSON data that I need to format into an HTML page where each parent becomes the header and its children are displayed under the same parent in the content area. Another parent will follow with its respective children listed below. How can I achiev ...

The property of Three.js Quaternion is immutable and cannot be reassigned

I'm attempting to develop a class (using three.js) that utilizes an array containing vector names to compare with an array containing a set of 3D vectors in order to generate a mesh of a flat face. However, I am encountering an error. Uncaught TypeEr ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

I need these buttons to determine which div is displayed or appears "on top"

I am facing a challenge with the buttons on one side of my webpage and a main content area occupying most of the page. My goal is to make clicking a button change the main content to a div that contains relevant information. However, I have struggled to f ...

An error occurred as the requested resource does not have the necessary 'Access-Control-Allow-Origin' header. The response code received was 403

I am working with Angular products services that make calls to the "http://jsonplaceholder.typicode.com/posts" URL using the HttpClient method. However, I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on t ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

The Slider.prepend() function in lightSlider is not functioning as intended for the 'onSliderLoad' event in lightGallery

I implemented lightslider with lightGallery in the onSliderLoad function. There are two sets of code snippets included in my HTML code. You can find the complete code on this jsfiddle link. Code 1: Displays lightGallery view on page load, rendering images ...

What is the significance of passing an argument within curly braces in the renderItem function of React Native's Flat List component?

This specific scenario entails: const blocks = [ {id: 0, content: 'HTML'}, {id: 1, content: 'CSS'}, {id: 2, content: 'JavaScript'}, {id: 3, content: 'React'}, {id: 4, content: 'Angular'}, ] c ...

Click on the button to add a new question and watch as another row magically appears

Working with ReactJS My goal is to display 10 rows by default, followed by a button labeled "Add a new question" which would create the 11th row. View current row image here Currently, only one row is being shown [referencing the image below]. I aim to ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...