The Handlebars template remains blank, failing to show any data or error messages

////////////////////////////////////
//  Function to append items  //
//////////////////////////////////

function addItems(data) {
    var template = document.getElementById('items').innerHTML;
    var handlebarsTemplate = Handlebars.compile(template);
    var compiledTemplate = handlebarsTemplate(data);
    document.getElementById('right').innerHTML = compiledTemplate;
}

///////////////////////////////////////
// Function to append list of items //
/////////////////////////////////////

function addList(data) {
    var listTemplate = document.getElementById('list').innerHTML;
    var handlebarsTemplate = Handlebars.compile(listTemplate);
    var compiledListTemplate = handlebarsTemplate(data);
    document.getElementById('left').innerHTML = compiledListTemplate;
}

/////////////////////////////////
//  AJAX call             //
///////////////////////////////

function fetchData() {
    var request = new XMLHttpRequest();
    request.open("GET", "/assets/data/items.json", true);
    function onReadyStateChange() {
        if(request.readyState === 4) {
            if(request.status >= 200 & request.status <= 400) {
                var data = request.responseText;
                console.log(data);
                addItems(data);
                addList(data);
            }
        }
    }
    request.onreadystatechange = onReadyStateChange;
    request.send();
}

and my Handlebars template is

<script type="x-handlebars-template" id="items">
    {{#each this}}
    <img src="{{img}}" class="{{class}}">
    <p class="{{class}}" id="{{pid}}">{{description}}</p>
    <a href="{{url}}" target="_blank">
        <button class="try {{class}}" style="max-width: 49%; float: left; margin-right: 1%;">Try It</button>
    </a>
    <a href="{{source}}" target="_blank">
        <button class="{{class}} try" style="max-width: 49%; float: right; margin-left: 1%;"><i class="fa fa-github" aria-hidden="true"></i> Code</button>
    </a>
    {{/each}}
</script>

and this is the sample data

[
     {
        "name": "Doinmin",
        "img": "assets/img/doinmin.png",
        "description": "This project started as a basic to-do app, but along the way I turned it into something that I use while practicing a musical instrument. The app can be used to deal with big tasks that can be broken down into smaller tasks, with each task being dealt
                with for a certain amount of time. It prevents you from getting overwhelmed. The app is built using HTML5, CSS3, and jQuery. <br>The app is not fit for android based browsers because the alarm function doesn't work in android browsers, it is not allowed.
                You may try the app or look up the source code on GitHub.",
        "url": "http://doinmin.com/",
        "source": "https://github.com/relentless-coder/Doinmin",
        "class": "doin",
        "pid": "dpara",
        "lid": "doin"
    },
     {
        "name": "Weather Clock",
        "img": "assets/img/weather.png",
        "description": "I built this app to practice CSS3 animations and improve skills in Angular.js. The app has clock, alarm clock, and weather functionality. This is an ongoing project, so more features will added in the future.<br> The app uses Angular.js, HTML, and
                CSS3. I have used Angular.js controllers and services for the functionality, transform animations, and media queries to change the layout for responsive design. You may try the app or look up the source code on GitHub.",
        "url": "weather.html",
        "source": "https://github.com/relentless-coder/weather",
        "class": "weather",
        "pid": "wpara",
        "lid": "weather"
    }
]

my template isn't displaying any data. I am not getting any error either. I am guessing it has something to do with the data that I've provided, but I tried explicitly parsing it to JSON, but that gave me an error

   Uncaught SyntaxError: Unexpected token 
 in JSON at position 331
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.onReadyStateChange (work.js:63)

Answer №1

Your issue pertains to your JSON file, which seems to contain irregular characters. To resolve this, consider replacing the content with the following:

[
     {
        "name": "Doinmin",
        "img": "assets/img/doinmin.png",
        "description": "This project initially started as a simple to-do app but evolved into a tool for practicing musical instruments. It helps break down big tasks into smaller ones, allowing you to focus on each task for a set time, thus preventing overwhelm. Built with HTML5, CSS3, and jQuery. <br>Note: The app may not work well in Android browsers due to the alarm function restrictions. For more information, visit the app or check the source code on GitHub.",
        "url": "http://doinmin.com/",
        "source": "https://github.com/relentless-coder/Doinmin",
        "class": "doin",
        "pid": "dpara",
        "lid": "doin"
    },
     {
        "name": "Weather Clock",
        "img": "assets/img/weather.png",
        "description": "Created this app to practice CSS3 animations and enhance skills in Angular.js. Features clock, alarm clock, and weather functionalities. Ongoing project with more features to come.<br>Utilizes Angular.js, HTML, and CSS3. Angular.js controllers and services are used for functionality, with transform animations and media queries for responsive design. Visit the app or view the source code on GitHub.",
        "url": "weather.html",
        "source": "https://github.com/relentless-coder/weather",
        "class": "weather",
        "pid": "wpara",
        "lid": "weather"
    }
]

To address the issue, start by cleaning up your data. Replace

var data = request.responseText;

With

var data = JSON.parse(JSON.stringify(request.responseText));

This adjustment should help resolve your problem.

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

It is not possible to retrieve a cookie via a request

Currently, I am in the process of setting up an Express JS server that uses cookies. This is my first time incorporating cookies into a project :) Upon user login, I send cookies to them using the following code: res.cookie('pseudo', list[i].ps ...

Is it possible to dynamically add plotLines to the xAxis using datetime in HighCharts?

Hey there! I've been playing around with adding plotlines in Highcharts and I'm loving it. It's really easy to define a date time on the xAxis for a plotline, like this: xAxis: { plotLines: [{ color: '#dadada', ...

What's the rationale behind receiving the second before the first?

I've been digging into ES6 promises, and I thought I had a handle on it for a moment. However, it seems like I may have hit a roadblock. What I'm aiming to do is handle a series of file operations where each operation depends on the completion o ...

Managing route rendering in nuxtjs: A guide

I came across Goldpage, a tool that allows for route rendering control. Render Control - With Goldpage, you have the flexibility to choose how and when your pages are rendered. For example, one page can be rendered to both HTML and the DOM (classic serv ...

I am able to input data into other fields in mongoDB, however, I am unable to input the

I am facing an issue with the password while everything else seems to be working fine. I am using a schema and getting an error, but it could be a problem in my functions because I hashed the password. I am unable to identify what's causing the issue. ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

What is the best way to generate automatic suggestions based on the data received from a JSON API?

One option for retrieving autocomplete suggestions is by utilizing the Amazon API: http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook The response from this query will include: ["facebook" ...

What causes the failure of making an ajax call tied to a class upon loading when dealing with multiple elements?

I can see the attachment in the console, but for some reason, the ajax call never gets triggered. This snippet of HTML code is what I'm using to implement the ajax call: <tr> <td>Sitename1</td> <td class="ajax-delsit ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file: cons ...

JQuery AJAX call not showing the outcome of PHP execution

I have a form that utilizes AJAX to send data to a PHP file for processing on the server-side and then returns the results. Check out the HTML form below: <div id="new_loc"> <form id="loc_form" method="post" action=""> <p><b> ...

Looping AJAX calls in Laravel

Encountering a persistent memory_limit loop issue while trying to store form data in the database has left me puzzled. The cause of this problem remains unclear to me, and I have been unable to find a solution despite adjusting the memory_limit in php.ini. ...

What is the best way to showcase an array of objects in a table with two columns?

Looking to showcase an array of objects in a table with 2 columns. What's the simplest way to achieve this display? const columns = [ { subHeading: "A", subText: ["1", "2"] }, { subHeading: & ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

Discovering country code details through the Geonames service API rather than relying on the HTML5 location object

My goal is to retrieve the country code of the user's current location using the Geonames Service API. However, it seems that the API only provides a two-letter country code instead of a three-letter one, which is what I require. To work around this i ...

Perform a sequence of test functions to display as individual tests on BrowserStack

I am faced with a challenge in my web application where I have a series of functions that simulate login and run through various features. These functions are written in JS using nightwatch.js and selenium via browserstack. The issue is that all the func ...