Error: JSON array contains unterminated string literal

Hey there,

 var favorites = 'Array (


[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
';

I've been encountering a syntax error - an unterminated string literal when I try to display the above content using console.log in JavaScript. I tried changing some characters and using regex patterns, but it seems like multi-line strings are causing an issue.

This dilemma began with an SQL query as seen below...

$favLinks = [];
$favQuery = "SELECT * FROM userfavorites WHERE users = '$username'";
$favResults = mysqli_query($conn, $favQuery);

while($row = mysqli_fetch_assoc($favResults)) {

array_push($favLinks, $row['fav_id']);

Then, I attempted this...

var favorites = <?php print_r ($favLinks); ?>

which resulted in the earlier mentioned problem.

If you have any suggestions on fixing this syntax error, I'd greatly appreciate it. Thanks!

Answer №1

Since multiline strings are not permitted in JavaScript:

"A
 B"

This will result in a syntax error. You can either replace the newlines with \n or use template literals like so:

`A
 B`

In your code snippet:

var newfavz =` <?php print_r ($favurl); ?>`;

Even though you fixed the error, the string is still not usable and needs to be parsed. Consider using JSON or creating your own parser.

Answer №2

To create a multiline string in JavaScript, remember to add a backslash at the end of each line:

const newFavorites = 'Array (\
[0] => ["6","1","2","5","3","4"]\
[1] => ["6","1","2","5","3","4"]\
[2] => ["6","1","2","5","3","4"]\
)\
';

Answer №3

To achieve the desired output, there are multiple approaches you can take:

One way is to utilize ES6 template literals:

var newfavz = `Array (

[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
`;

Another option would be to use a backslash for line breaks:

var newfavz = 'Array (\n\
\n\
[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
\n)\
';

You can also concatenate strings to achieve the desired format:

var newfavz = 'Array (\n' +
'\n' +
'[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'\n' +
')\n';

The symbol \n represents a newline character in this context.

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

Stuck with the Same Theme in the AppBar of material-UI?

Currently, I am attempting to modify the theme of a material-UI AppBar by utilizing states. Strangely enough, although the icons are changing, the theme itself is not. If you'd like to take a look at the code, you can find it here: https://codesandbo ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...

Discovering the operating system and architecture type for my browser using Node.js - what steps should I take?

I am currently developing a Node.js app that serves as an API microservice. I need to retrieve the operating system and architecture type from a GET request made by my browser. One example could be: "Windows NT 10.0; Win64; x64" ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". Upon clicking on the link referring to "external 'url': 1", it led ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

What is the best way to transfer a variable from jQuery to a PHP script?

While I am aware that similar questions have been asked in the past, I am facing a unique challenge in trying to create a table with distinct links and pass the id of the link to a PHP page. Here is what I have so far: echo("<p>To reser ...

Is the string data in JSON format stored in SharedPreferences globally saved?

What is the best practice for storing global data in Android - saving it as a JSON format String and accessing it through SharedPreferences when needed? ...

When it comes to implementing Ajax and Json in Ruby on Rails, the action url can sometimes be a

Apologies for any language issues. I am wondering about using "get" in JQuery when the url is an action reachable from the browser. In my js file: $.get('/user').success(function(data) { availableTags = data;} ); This is my controller: class U ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

How to Delete Decimal Points from a String Using Regular Expressions

I am searching for a way in JavaScript, such as REGEX, to eliminate decimal numbers from a string. Here is an example input: Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST Mercedes C63 AMG Sound REVVING 6,3l V8 And here is the expected output: M ...

Jinja: generating recursive json outputs

I am having trouble rendering this specific json object using the jinja template engine view full json object here Shortened version: { "data": { "domain.org": { "type": "folder", "children&q ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

"Enhance Your Website with Drag-and-Drop Cart Functionality using HTML

Seeking assistance from anyone who has the knowledge. I've searched through similar questions on this platform but haven't been able to resolve my issue. Currently, I'm working on developing a basic shopping cart using HTML5 (Drag and Drop ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

Uncover the contents of a JSON array by employing generics and leveraging the power of

I'm currently working on an app to gain a better understanding of using generics in Swift. To achieve this, I decided to utilize Studio Ghibli's API Here's my approach: Send a request to the API Receive the response Parse the JSON data T ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

Navigating through dynamic elements using Selenium

I'm having trouble extracting boxer information from the flashcore.com website using Selenium. The code I've written doesn't seem to be working properly. Can anyone point out where the error might be? The expectation is that Selenium should ...

Obtaining the latest record ID from MySQL using node.js

I am currently working on a project where I need to add new user information to a MySQL database. I'm looking for a way to retrieve the ID of the most recently added record so that I can create login details for the user. The environment in which this ...