What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck.

My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u".

Could someone please point out where I went wrong? Thanks in advance!

// Display all current contacts when the page loads
$(document).ready(function(){

    // Check if localStorage database exists
    if(!localStorage.getItem("customerDatabase")){

        // Create a JSON object to store addresses
        var contacts = {
            "users":[
                {
                    "id":"1",
                    "name":"dennis",
                    "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c7c6cdcdcad0c1ccdad0e3c4cec2cacf8dc0ccce">[email protected]</a>"
                },
                {
                    "id":"2",
                    "name":"zoe",
                    "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="344e5b515d47525159555851745359555d581a575b59">[email protected]</a>"             
                }
            ]   
        };

        // Convert the object to a string 
        var stringObject = JSON.stringify(contacts);                

        // Store it in localStorage
        var storedDatabase = localStorage.setItem("customerDatabase", stringObject);                                            

    } else {
        // List all customers on page load
        listJSONCustomers();        
    }   

    // Function to display all contacts from JSON object in localStorage
    function listJSONCustomers(){

      var displayHTML = "";
      var i;

      // Get data from localStorage
      var storedDatabase = localStorage.getItem("customerDatabase");

      // Parse the data to a JSON object
      var parseObject = JSON.parse(storedDatabase); 

      // Access the users key of the JSON object
      var userObject = parseObject.users;

      // Get the number of customers in the database
      var contactsLength = userObject.length;     

      for(i=0; i<contactsLength; i++){
          var trElement = '<tr id="address' + (i+1) + '">';
          var tdId = '<td id="id' + (i+1) + '">' + userObject[i].id + '</td>';
          var tdName = '<td id="name' + (i+1) + '">' + userObject[i].name + '</td>';
          var tdEmail = '<td id="email' + (i+1) + '">' + userObject[i].email + '</td>';
          var tdButton = '<td id="button"><button id="editButton' + userObject[i].id + '">Edit</button> | <button id="deleteButton' + userObject[i].id + '">Delete</button></td>';

          displayHTML += trElement + tdId + tdName + tdEmail + tdButton + '</tr>';
      }     

      $('#address_list').html(displayHTML);           
    }       

    // Add customer to the database  
    $('#saveCustomer').click(function(){

       if( $('#customerName').val() !== "" && $('#customerEmail').val() !== "" ){

           var customerName = $('#customerName').val();
           var customerEmail = $('#customerEmail').val();

           // Get data from localStorage
           var storedDatabase = localStorage.getItem("customerDatabase");

           // Parse the data to a JSON object
           var parseObject = JSON.parse(storedDatabase);    

           // Access the users key of the JSON object
           var userObject = parseObject.users;     

           // Create new entry
           var newCustomerObject = {
                                  "id": userObject.length + 1,
                                  "name": customerName,
                                  "email": customerEmail
                                  };

           // Add the new entry to the object                                                            
           userObject.push(newCustomerObject);

           // Convert the object to a string for localStorage
           var stringObject = JSON.stringify(parseObject);         

           // Store the JSON object in localStorage
           var storedDatabase = localStorage.setItem("customerDatabase", stringObject);

           // List all customers again whenever a new entry is added
           listJSONCustomers();     

       } else {
          alert("Please enter the customer's name and email.");  
       }

    }); // End of $('#saveCustomer').click();


});

Answer №1

There was a moment in time when the value of your LocalStorage key got corrupted due to an error in your code. LocalStorage is only able to store strings, so if you accidentally input something other than a string, it will be converted into one. The fact that your value is shown as 'undefined' indicates that you might have mistakenly carried out the following action at some point:

var value;
localStorage.setItem('key', value);

In this scenario, the variable value holds undefined, which is not a string. When saved, it will be converted, leading to a problem since "undefined" is not valid JSON. Consequently, any parsing attempt will result in an exception being thrown.

To resolve this issue, you should remove the problematic value with the removeItem method:

localStorage.removeItem("customerDatabase");

Answer №2

Encountered a similar issue when transferring content from the Notes app and executing in Chrome dev tools.

Resolved the problem by switching to VScode for temporary storage 🤷‍♂️

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

Implementing JSON object parsing within a Liferay hook

Currently, I am working on developing a hook where I need to parse a JSON string. My initial thought was to use the json-simple API for this purpose, so I included the corresponding JAR in the build path. However, upon deploying the hook, an error message ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Traverse through the JSON object in PHP

I have a piece of code that loops through a JSON object. The goal is to display one object from the JSON if isset($_GET['latest=1'])), and 15 objects if latest=15. How can I achieve this? <?php header('Content-Type: application/json&apos ...

Unraveling the Secrets of JSON in Swift

Lately, I've been struggling to decode a JSON file within a UIKit app but have faced failure every time I tried. Could someone please lend me a hand? Here's my decoding function: override func viewDidLoad() { super.viewDidLoad() ...

formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is: vx = Math.floor(Math.random() * 20) vy = Math.floor(Math.random() * 20) Howev ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

Send a PHP array to JavaScript to display a horizontal pop-up submenu on hover

Currently, I am engaged in the process of updating an old website. I have made modifications to the html, php, and switched from a MySQL database to an SQL database. All seems to be going well in these areas. My expertise lies in databases, PHP, SQL, and I ...

How can you retrieve a value from a JavaScript closure function?

I'm struggling with getting a value from a closure function in Javascript. In my initial attempt, I placed the return statement inside the inner function, but it was not effective. Then, I tried moving the return statement to the outer function, howev ...

After closing and reopening the jQuery modal, the name does not appear

I crafted a custom modal window to display images along with comments and the owner's name. The issue arises when I close the current modal and reopen it; the owner's name disappears. Oddly enough, the name is displayed the first time the modal i ...

Navigating through ajax requests on a Leaflet map

Currently, I have a leaflet map set up with the leaflet-panel-layers plugin to create a visually appealing layer control. To create my layers and overlays, I have two functions in place. The issue arises when trying to access external geoJSON files, as lea ...

Utilizing dynamic class and color binding features in VueJs?

I need help with implementing a Custom Sort method on my divs to arrange them in ascending or descending order. My query is how can I pre-set the icon color to grey by default, and only change it to black when clicked, while keeping the others greyed out a ...

Setting the position of a tooltip relative to an element using CSS/JS

I'm struggling to make something work and would appreciate your help. I have a nested list of items that includes simple hrefs as well as links that should trigger a copy-to-clipboard function and display a success message in a span element afterwards ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...

Divide the pair of arrays that are transmitted via JSON

I combined two arrays and passed them through JSON, as shown below: $result = array_merge($json, $json1); echo json_encode($result); Now, to retrieve the data, I am using the following code: $.getJSON('./tarefasaad52', function (data) { } How ...

Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, bu ...

How to Store and Retrieve User-specific Data using Express and Mongoose?

Currently, I am developing a small single-page application that allows users to login using PassportJs and Mongoose. One of the main features I am working on is enabling users to log in and have a unique todo/task list associated with each user. I succes ...

Manage and modify data values

Currently, I am developing a weather forecast app and facing an issue with changing the temperature from Celsius to Fahrenheit upon hovering. Despite my attempts, the changes I make either do not reflect or completely erase the line. I am eager to learn ...

JavaScript Method for Retrieving Form Element Values

I am currently working on retrieving the value of an input element in a popup window that is launched from a parent page. Here is my code, but I am facing difficulties in obtaining the pc value from the input field. <html> <head> <? $pid= ...