An issue occurred while attempting to read words from JSON file

My current issue involves loading words from JSON into my webpage. The images are functioning properly, thankfully.

I have already successfully loaded the necessary images through JSON onto my webpage. However, I am still in need of loading words through JSON onto my webpage.

{"main_object": {
    "imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
    "wordsJ": ["næb", "kat", "æg", "mel", "mælk", "pas", "ske", "te"]
}
}

var jsonData = "noJson";
var hr = new XMLHttpRequest();

$(document).ready(function(){
var jsonData = 'empty';
  $.ajax({
    async: false,
    url: "./js/data.json",
    dataType: 'html',
      success: function(response){
        jsonData = JSON.parse(response);

        console.log('ok');
          imagesJ = jsonData.main_object.imagesJ;
          wordsJ = jsonData.main_object.wordsJ;

          for(i = 0; i < imagesJ.length; i++) {
            images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
          }
          document.getElementById('images') = html;

           for (i = 0; i < wordsJ.length; i++) {
              wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';  
           }
             document.getElementById('words') = html;

      },
      error: function(){
        console.log('JSON could not be loaded.');
      }
    });
        console.log(jsonData);


});
header {
  height: 5%;
}

body {
  background-color: #f0f0f0;
}
.container {
  height: 90%;
}
.images img {
  height: 100px;
  width: 100px;
}
footer{
  height: 5%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sleepopdracht</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/css.css">
</head>
<body>
  <header>

  </header>

    <div class="container" id="container"><div class="images" id="images"></div>
                                          <div class="words" id="words"></div>
    </div>


  <footer>
  </footer>
    <script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>

The Javascript code displays how I attempted to load the words similar to the images. While it should work seamlessly, the console keeps reporting an

Uncaught ReferenceError: Invalid left-hand side in assignment ~ jquery.min.js:4

I have been unable to pinpoint the source of the problem or find a solution. Even with the Words loop section commented out, the error persists. Previously, the code ran without issues before implementing the Words Loop.

Answer №1

It appears that you have not yet defined imagesJ and wordsJ variables.

var imagesJ;
var wordsj;

In order to address this issue, consider implementing the following solution:

   var word = document.getElementById('words');
   var html = '';
   for (i = 0; i < wordsJ.length; i++) {
      html += '<span>' + wordsJ[i] + '</span>';  
   }
   word.innerHTML = html;

Update to the Final File:

var jsonData = "noJson";
var hr = new XMLHttpRequest();
var imagesJ;
var wordsj;

$(document).ready(function(){
var jsonData = 'empty';
  $.ajax({
    async: false,
    url: "./js/data.json",
    dataType: 'html',
      success: function(response){
        jsonData = JSON.parse(response);

        console.log('ok');
          imagesJ = jsonData.main_object.imagesJ;
          wordsJ = jsonData.main_object.wordsJ;

          for(i = 0; i < imagesJ.length; i++) {
            images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
          }
          document.getElementById('images') = html;

        var word = document.getElementById('words');
        var html = '';
        for (i = 0; i < wordsJ.length; i++) {
            html += '<span>' + wordsJ[i] + '</span>';  
        }
        word.innerHTML = html;
      },
      error: function(){
        console.log('JSON could not be loaded.');
      }
    });
        console.log(jsonData);


});

Answer №2

Consider updating this block of code:

 var words = document.getElementById('words')
 for (i = 0; i < wordsJ.length; i++) {
     words.innerHTML += '<span>' + wordsJ[i] + '</span>';  
 }

Answer №3

After some investigation, I was able to pinpoint the issue.

 document.getElementById('images') = html;

This line of code was incorrect, as I had not actually called html beforehand. To rectify this, I added a console log of html with an empty string.

      console.log('ok');
       var imagesJ = jsonData.main_object.imagesJ;
       var wordsJ = jsonData.main_object.wordsJ;
       var html = '';
       var html2 = '';

The variable html2 is specifically for the words.

I discovered that my document.getElementById call was incomplete (this was the root cause of the error).

The corrected code for updating the document is as follows:

document.getElementById('images').innerHTML = html;

Additionally, I realized that this line:

images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';

should be revised to:

html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';

Therefore, my updated code looked like this:

  var jsonData = "noJson";
  var hr = new XMLHttpRequest();

   $(document).ready(function(){
   var jsonData = 'empty';
   $.ajax({
   async: false,
   url: "./js/data.json",
   dataType: 'html',
   success: function(response){
    jsonData = JSON.parse(response);

    console.log('ok');
      var imagesJ = jsonData.main_object.imagesJ;
      var wordsJ = jsonData.main_object.wordsJ;
      var html = '';
      var html2 = '';

      for(i = 0; i < imagesJ.length; i++) {
        html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
        //images.innerHTML += '<img    src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
        }
        document.getElementById('images').innerHTML = html;
        //$('#images').append(html);


        for (i = 0; i < wordsJ.length; i++) {
          words.innerHTML += '<span>'+wordsJ[i]+'</span>';
         }
        document.getElementById('words').innerHTML = html2;

    },
    error: function(){
      console.log('JSON could not be loaded.');
    }
  });
      console.log(jsonData);


});

While I still need to address the issue of displaying words in the browser, I have successfully resolved the error. Thank you to everyone who helped! Happy programming! :D

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

Updating the state on a click event triggered by a MenuItem in React using Material UI

I'm currently working on implementing state changes based on dropdown selections using Material UI. However, I've encountered an issue where the code snippet below (simplified) only returns the list item, and I'm unsure what steps to take n ...

Stylesheet compilation with SCSS scripts

I am facing an issue with prefix:css. I am not very familiar with the scss build process, so if anyone knows what the problem is, please help me out. "watch:sass": "node-sass src/styles/global.scss src/assets/css/style.css -w", ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

Utilize *ngFor in Angular 9 to showcase both the key and values of an array

JSON Data { "cars": { "12345": [1960, 1961, 1962], "4567": [2001, 2002] } } HTML Template <strong>Plate and Year</strong> <div *ngFor="let car of cars"> {{car}} </div> This should be di ...

Alter the background hue of a specific column within a SharePoint list

I've been struggling to modify the background color of a column within my Sharepoint list, but I haven't quite achieved the desired outcome. Even though I've attempted using the JSON code provided below, it's frustrating that it doesn& ...

Step-by-step guide to setting up Angular 2 with fullpage.js scrolloverflow

I am currently working on a project using Angular 2 that incorporates the fullpage.js port from https://github.com/meiblorn/ngx-fullpage. I am facing an issue with implementing scrolloverflow on a specific section and could use some guidance. I have alread ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Discover the best method for choosing a row that aligns with the content inputted into the row's input tag

I have a table where rows are added dynamically, each containing text boxes. I want to check if the value in the new row matches any previous rows before adding it to the table. If there is a match, I need to update another textbox in the current row. Othe ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Setting the minimum width for a grid item in a React Material UI component

Is there a way to ensure that a material-ui Grid item has a minimum width of 250 pixels? I've tried using the sizing suggestions from Material UI's documentation, but haven't had any success. The 'logo' element within the Grid cont ...

In my Django html file, I am facing an issue with the IF statement that seems to be dysfunctional

I have a like button and I want it to display an already liked button if the user has already liked the post. Here is my HTML: {% for post in posts %} <div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4"> & ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari. ne ...

The button in the flex container is not wide enough due to center alignment

For my project, I implemented a CSS grid layout consisting of 20 rows and 20 columns (5% of screen for each cell). One particular page includes a button that initially fit within grid columns 5-8 and rows 6-9 without any issues. However, I wanted to center ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Tips for properly passing data from Ajax to PHP and extracting value from it

I'm curious about how to receive a value from Ajax and then send that value to PHP. Can anyone provide some guidance on this? Specifically, I need the percent value obtained from Ajax to be sent to $percent for option value. <div class="form-g ...

Is it possible to secure my JSON data with encryption?

Currently, I am working on a JQuery web application that is intended to run locally from a DVD. This application's functionality involves parsing the contents of a JSON file. I am seeking advice on secure methods for encrypting or obfuscating the JSO ...

Looking to modify the styling of links in an unordered list?

Let me explain what I attempted to accomplish CSS: li:nth-child(2n) { background-color:gray; } HTML: <ul> <li><a></a></li> <li><a></a></li> <li><a></a></li> ...