Error encountered in parsing JSON: abrupt end of data (JavaScript)

I have been working on a few functions that are responsible for parsing JSON data, both external and internal, and displaying it on a local webpage using the localStorage feature. While I have successfully displayed the external JSON data, I am running into an issue when trying to submit and parse locally stored JSON data, resulting in a

JSON.parse: unexpected end of data
error. The function in question here is retrieveData().

Here is an overview of what I am attempting to achieve.

function saveData() {  
    getRadio();
    getCheckbox();
    localStorage.setItem("Categories", $("select").value);
    localStorage.setItem("Name", $("Name").value);
    localStorage.setItem("Rating", $("rating").value);
    localStorage.setItem("Recommend", recommendValue);
    localStorage.setItem("Favorite", Favorite);
    localStorage.setItem("Date", $("date").value);
    localStorage.setItem("Notes", $("notes").value);
    alert("Resource Saved!");
}

function getRadio() {  
    var radio = document.forms[0];
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            Favorite = radio[i].value;
        }
    }
}

function getCheckbox() { 
    if ($("Y").checked) {
        recommendValue = $("Y").value;
    }
    else {
        recommendValue = $("N").value;
    }
}

function retrieveData() { 
    toggle("on");
    if (localStorage.length === 0) {
        alert("No data in localStorage. Adding default data.");
        fillData();
    }
    var Makediv = document.createElement('div');
    Makediv.setAttribute("id", "games");
    var list = document.createElement('ul');
    Makediv.appendChild(list);
    document.body.appendChild(Makediv);
    for (var i = 0; i < localStorage.length; i++) {
        var mli = document.createElement('li');
        list.appendChild(mli);
        var keyVal = localStorage.key(i);
        var value = localStorage.getItem(keyVal);
        var objct = JSON.parse(value);
        var makesul = document.createElement('ul');
        mli.appendChild(makesul);
        for (var q in objct) {
            var msl = document.createElement('li');
            makesul.appendChild(msl);
            var subText = objct[q][0] + " " + objct[q][1];
            msl.innerHTML = subText;
        }
    }
}

function fillData() { 
    var xmlRequest;
    if (window.XMLHttpRequest) {
        xmlRequest = new XMLHttpRequest();
    }
    else {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlRequest.onreadystatechange = function () {
    if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
        var text = xmlRequest.responseText;
        var json = JSON.parse(text);
    }
    xmlRequest.open("GET", "json.js?_dc" + Math.random(), false);
    xmlRequest.send();
    for (var i in json) {
        var ID = Math.floor(Math.random() * 100000001);
        localStorage.setItem(ID, JSON.stringify(json[i]));
    }
}

function $(x) { 
    var element = document.getElementById(x);
    return element;
}

var DisplayRatings = $('DisplayLink');  
DisplayRatings.addEventListener("click", retrieveData); 
var SubmitRating = $('submit');
SubmitRating.addEventListener("click", saveData, true); 

Can anyone offer some guidance on this issue? I have tried using JSON.readyStatus === 4 and JSON.status === 200 without success, within an if statement.

My goal is to have this functionality integrated into the existing addGame.html page. The expected outcome is to display the data in an unordered list format with the saved JSON data. Below is a snippet of the JSON data stored in the json.js file.

{
    // JSON data here
}

The addGame.html file contains the form structure to input data for the JSON object.

Upon calling the retrieveData() function, the expected output should resemble the following structure:

  • Category
    - Name
    - Rating
    - Recommend
    - Favorite
    - Notes

However, the actual output I am experiencing looks like this:


  • *
    *
    *
    *
    *

I am solely using JavaScript, Ajax, HTML, and CSS for this project. The issue seems to be specifically related to handling JavaScript and HTML to save JSON data from the form and display it on the addGame.html page.

UPDATE: I have also attempted using JSON.stringify() when reading values from the submitted form, but the same error persists.

Answer №1

The code inside json.js is written in javascript, not JSON. The correct way to start a json object is by not using 'var json = {' but simply '{'.

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

What is the method to switch between radio buttons on a webpage?

Here is an example of HTML code: <input type="radio" name="rad" id="Radio0" checked="checked" /> <input type="radio" name="rad" id="Radio1" /> <input type="radio" name="rad" id="Radio2" /> <input type="radio" name="rad" id="Radio4" /& ...

Retrieving a variable in a JavaScript function while a webpage is in the process of loading

Recently, I was working on writing Selenium test cases in C# and encountered an issue while trying to capture a value from a webpage. The problem arose when the retrieved value was rounded to 5 decimal points which was not what I wanted. Instead, I needed ...

Encountering a surprise syntax error while trying to reference JavaScript from HTML?

After downloading this code from Github to make some modifications, I decided to run it locally. Link to the downloaded file The main index.html file references the JavaScript using: <script type="text/javascript" src="app.0ffbaba978f8a0c5e2d0.js">& ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

Optimizing Require.js File for Efficient Loading

I have successfully implemented require.js with multiple individual files: require(['app/login/Login'], function (app) { new app.Login(); }); Everything is functioning as expected, with each module loading when needed. Recently, I have opti ...

The attempt to cast the value of "X_Value" to an ObjectId in the "X_Model" model at the path "_id" has failed due to being of type string

I'm facing an issue while attempting to update multiple records simultaneously using their IDs. The error message I encounter is puzzling, even ChatGPT couldn't provide a solution. Here's the error: Cast to ObjectId failed for value " ...

Having trouble with uploading a video file using js chunking upload and php for files over 10mb

The code I wrote for chunk upload using JS and PHP works fine when uploading a video file less than 10MB. However, when trying to upload a 17.6MB video file, the file uploads successfully but the video cannot play. I have added error handlers in both PHP a ...

Linking a variable to a class in C# for the purpose of handling JSON data

For a project I'm working on, I need to fetch JSON data from an API and deserialize it using DataContract classes. Each URL corresponds to a different JSON output for the API. My question is, is there a more efficient way to map URLs to DataContract ...

Encountered an error when attempting to use 'appendChild' on 'Node': the first parameter is not the correct type. It was able to work with some elements, but not with others

I'm currently working on a script that utilizes fetch to retrieve an external HTML file. The goal is to perform some operations to create two HTMLCollections and then iterate over them to display a div containing one element from each collection. Here ...

Extract data from JSON object

My JSON object is called idAndNames.json; [ { "id":"1", "name":"name1"}, { "id":"2", "name":"name2"}, { "id":"3", "name":"name3"} ] I'm looking to filter it by ID and name function applyFilter(id, valueItem) { return id <= valueIte ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...

JSON input in react.js sadly ended abruptly

I am encountering a problem when I attempt to submit the form. Unhandled Rejection (SyntaxError): Unexpected end of JSON input Whenever I press the submit button, this error occurs, here is the code snippet: onButtonSubmit = () => { this.setState({ ...

Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure: --Events ----Races -------Participants Below is some dummy data example that represents the type of data I need to store in Firebase: var dummyData = [ { ...

Analyze data with diverse structures using crossfiltering technology

Exploring the world of crossfilter is a new adventure for me as I am just starting out and have limited experience with handling data. The data I am working with has a varying structure, as shown below: const data = [ {_id: 001, a: 10, b: 11, c: 12}, ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

The $scope variable fails to reflect updates in the view following a broadcast event triggered by a

I have been troubleshooting a similar issue and I can't seem to figure out why the update is not reflecting in the view. While I am able to see the scope variable updating in the catch events logs, the changes are not being displayed in the view. For ...

Adjusting the devicePixelRatio in Three.js to optimize rendering with CSS3DRenderer

I am looking to display a <div> element (specifically, one from the ECharts library) using the Three.js CSS3DRenderer and combine it with WebGL content. However, I have noticed that when the <div> has fixed width and height, the rendering qua ...

Dividers afloat - expanding current script with multiple additions

I am currently utilizing this website as a hub for showcasing my various web projects. The jsfiddle code provided in response to this particular inquiry is exactly what I need, however, I am unsure of how to have multiple divs moving simultaneously acros ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Troubleshooting CSS appendChild not functioning as anticipated

I'm attempting to manually input CSS for font-face in a new window with the following code: const css = '@font-face {font-family:Roboto; src:url("assets/fonts/Roboto-Black.ttf");}'; const head = this.externalWindow.document.getElementsByTag ...