Filling in the fields based on the data in the JSON

  1. I prefer not to rely on jQuery for this task.
  2. If possible, I would like to maintain the presence of <mytag>.

The JSON data structure I am working with is as follows:

{
    "datas": [
        {
            "id": "hotel_name",
            "value": "My hotel name"
        },
        {
            "id": "hotel_description",
            "value": "My description"
        }
    ]
}

Based on this JSON, my objective is to populate the following html tags with the respective content:

<mytag id="hotel_name"></mytag>
<mytag id="hotel_description"></mytag>

Resulting in:

<mytag id="hotel_name">My hotel name</mytag>
<mytag id="hotel_description">My description</mytag>

Here is what I have attempted so far:

function createElements(elements) {
    elements.datas.forEach(function (element) {
        var div = document.getElementById(element.id);
        div.innerHTML = element.value;
    });
}

var request = new XMLHttpRequest();    
request.onload = createElements;
request.responseType = "json";
request.open("GET", "datas.json", true);
request.send();

Answer №1

There are a couple of issues to address:

  1. The response must be obtained from request.responseText and not passed to onload().

  2. Prior to using the JSON response, it needs to be parsed into an object by utilizing JSON.parse().

  3. It is recommended to comment out the line request.responseType = "json";, as it appears to trigger the confusing error

    InvalidStateError: DOM Exception 11
    .

The correct approach is shown below:

function createElements(elements) {
    elements.datas.forEach(function (element) {
        var div = document.getElementById(element.id);
        // NOTE: To avoid errors when encountering unexpected elements, ensure that `div` is not null.
        if (div != null) {
            div.innerHTML = element.value;
        }
    });
}

var request = new XMLHttpRequest();    
request.onload = function() {
    var elements = JSON.parse(this.responseText); // Parse response.
    createElements(elements);
}
//request.responseType = "json"; // <-- Omit this line.
request.open("GET", "datas.json", true);
request.send();

Answer №2

Here is an alternative response:

<!DOCTYPE html>
<html>
<head>
    <title>your title</title>
</head>
<body>

<mytag id="hotel_name"></mytag>
<mytag id="hotel_description"></mytag>


<script type="text/javascript">
window.onload  = function (){   
   var json = {"datas": [{"id": "hotel_name", "value": "My hotel name"},
                         {"id": "hotel_description", "value": "My description"}
                        ]
              };

    var id="";
    var value = "";


    for(var i=0;i<json.datas.length;i++){

        id = json.datas[i].id;
        value = json.datas[i].value;
        document.getElementById(id).innerHTML = value;
    }

}
</script>
</body>
</html>

Moreover, why are you considering using "mytag"? If you opt for "mytag," your document will be considered as non-valid HTML content

Attempt to validate this HTML content through the HTML validator

After validation, you will receive the following message:

It is advisable to use established HTML tags like div, span, section etc in order to have a valid HTML content.

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

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

Transferring map functionality to a separate file

Is it possible to export the function inside the orders.map, specifically 'order', and then import it into another JS file with a function inside? I keep receiving an error that order is not defined. Thank you main.js const getReport = asy ...

Stop the form from refreshing upon submission using an Ajax call in AngularJS

Currently, I am in the process of developing a search form that requires two inputs: Job title and Location. These keywords are used to gather data from various websites. However, upon submitting the form, the page refreshes itself. To prevent this, I have ...

Tips for creating a partial matching filter on an array using elements from a separate array

My goal is to filter an array by finding partial matches from another array. To illustrate, consider the following arrays: Array1 = categories: 292300, categories: 300, categories: 292500280 Array2 = 300, 498 After filtering, ...

Storing data in the browser's local storage using jQuery without requiring any CSS

I have a form that receives data and I am trying to save the first two pages of received data into localStorage: <form id="myForm" method="post"> Font Size (px): <input id="fontsize" type="text" name="fontsize" /> </form> <s ...

What is the reason this JavaScript code functions properly within a <script> tag but not when placed in a separate .js

After researching various image sliders online, I came across this specific one. It worked perfectly fine when I included the JavaScript directly in a script tag within the HTML file. However, as soon as I tried to link it via a .js file, the slider stoppe ...

Hide the address bar in a Google Maps iFrame

After numerous attempts, I still can't seem to hide the address bar on this Google Maps iFrame. Can anyone provide a solution or workaround for this issue? https://i.sstatic.net/x0pl9.png I have tried using display:none; in our CSS, which successfull ...

Guide to displaying a component within the Vue instance

I am currently in the process of developing a Nuxt module that will not interfere with the main Nuxt application. My approach involves creating a separate Vue instance and mounting it as a child node under the body element, similar to a child node to the _ ...

Inject a heavy dose of Vue into your project

**I'm trying to implement the provide/inject logic in Vue. In my 'App.vue' component, I have defined the 'firstName' input as a string "John", and I want to display this value when the child component 'Step1' is created. ...

"Encountering a problem with ThreeJs graphics rendering

I recently developed an application using ThreeJs, but I encountered a strange issue. After rendering the 3D graphics, the window appears blank. However, when I click on full screen or adjust the window size, the output becomes visible. Check out Screen s ...

javascript mobile nav event

My website utilizes a bootstrap feature for mobile devices where a left sidebar pops up when clicking a button. I am not very familiar with bootstrap, but I would like to link a javascript event to determine if the left sidebar is visible. How can I achiev ...

The data returned by my select query is identical across three rows

When running my code, I am encountering an issue where the values for the 1st, 2nd, and 3rd columns are all the same. Additionally, the output that should be in the second column is mistakenly appearing in the first row. <?php require "db.php"; $s ...

Unexpected JSON data received compared to JSON data sent in Spring Rest and Hibernate

I'm facing challenges with integrating Spring Rest and Hibernate into my Android application. Specifically, I am encountering an issue with one of the POST calls in my API requests. In my project, I have two main classes: Player and Game. @Entity @T ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

Discover the best way to reference a JavaScript variable within an HTML form textfield

I'm having trouble with a script that is supposed to display the selected value from a drop down list in a text field on an HTML form. When I select an option, the value is not appearing in the text field. Can someone please assist me with this issue? ...

Performing an asynchronous Ajax call from a partial view in an Asp.net MVC application

Is it possible to use Ajax to fetch data from a form located in a partial view, send it to a controller, and receive a response message? Utilizing Ajax $("#submitContactInfo").on("click", function () { if ($('#contact-form').valid() === true) { ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...