Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below:

<td onclick="openFile('<?php echo htmlentities ($row['name'])?>','
                      <?php echo htmlentities ($row['content'])?>')">
    <a href="#nf" data-toggle="tab"><?php echo $row['name']?></a></td>

When there is an endline character in $row['content'], the problem arises:

openFile('wow','wow wow

wow ');

If the browser cannot find a closing quote on the same line, it will trigger an error (SyntaxError: unterminated string literal [Break On This Error]).

Is there any solution to this issue?

Answer №1

To eliminate it, simply replace it with an empty space,

str_replace("\n","",$row['name']);

If you want to retain the line break in your JavaScript string, you can use double backslashes to escape it,

str_replace("\n","\\n",$row['name']);

Answer №2

I encountered a similar issue in the past. Utilizing json_encode in PHP and JSON.parse() in JS helped me to overcome it. To address your specific situation, consider implementing the following code:

<td onclick="openFile('<?php echo htmlentities ($row['name'])?>','
                  <?php echo json_encode($row['content'])?>')">
<a href="#nf" data-toggle="tab"><?php echo $row['name']?></a></td>

In your openFile() function, you can then parse the content parameter using JSON.parse() as shown below:

function openFile(name, content){
     content = JSON.parse(content);

    ....
     // insert your custom logic here

}

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

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

Can Eloquent Model JSON Method Include Null Values?

Is there a way to print a Laravel Eloquent Model with null values? I am looking to generate a new Question object that includes all fields, but with null values. However, when I attempt this, it only prints an empty array, []. var app = new Vue({ el: ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

Loading a gallery dynamically using AJAX in a CakePHP application

I am currently working with Cakephp 2.8.0 and I am facing an issue with implementing ajax in my application. I have a list of categories displayed as li links, and upon clicking on a category, I need to remove certain html code, locate the necessary catego ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Switch tabs with JavaScript

I'm encountering an issue with changing tabs using JavaScript and Ajax. The script I have works when not using Ajax but fails to work properly with it. Here is the script: $(document).ready(function(){ $("#mtabs li").click(function() { ...

Update of component triggered only upon double click

I'm encountering an issue with my parent component passing products and their filters down to a subcomponent as state. Whenever I add a filter, I have to double click it for the parent component to rerender with the filtered products. I know this is d ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Refreshing a Vue JS component

As a beginner in VueJs, I am facing an issue with reloading a component and table when a refresh button is clicked. I have tried using the forceUpdate method and changing keys, but it has not been successful so far. If anyone has any suggestions on how to ...

Fixing the Material UI upgrade error: "Make sure you have the right loader for this file type."

As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

The new and improved Vue 3 computed feature in the Composition API

The temporary object appears as: tmp : { k1: { k2 : { k3 : [abc, def] } } To access k3 in the setup, it should be: tmp.value.k1.k2.k3[0 or 1]. I am looking to change its name to something like - k3_arr = tmp.value.k1.k2.k3; Within my Vue single componen ...

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...