Javascript multiline string causing "SyntaxError ILLEGAL" - javascript

I have a very basic function on a template that shows an alert message:
<script>
function detailer(pii_other){
alert(pii_other);
}
</script>
it is called with a string value like this:
<td><button onclick="detailer('{{other}}')">Details</button></td>
It works fine on most cases but I saw that it sometimes fails based on the content of 'other'. Uncaught SyntaxError: Unexpected token ILLEGAL on the Chrome Javascript console.
[Edit:]
I am reading the other content from a RESTful API service that returns JSON, in this case the other field has this content:
body: {
other: ""address_street"=>"江西省九江市共青城市 账号 2123123912391239 户名 齐少楠", "name"=>"test""
}
How can I prepare my code to support multiline strings in the alert ? I have no way to restrict the data input in the form.

I would do the same thing Daniel A. White suggested - convert the new lines to some string that won't evaluate to a 'real' new line in your templating engine (Jinja?). You may have to escape the new line character so that it stays on one line.

Related

Javascript textarea line break into database for result as JSON String

I want to save the textarea line breaks to the database (Mongoose - MongoDB latest). For frontend I'm working with iQuery or simple Javascript.
I'm getting currently the following error message from json parse
VM533:1 Uncaught SyntaxError: Unexpected token
in JSON at position 207
at JSON.parse ()
at profil:390
Json line which created this error
"My name is example
My name is example"}
In my Database is no \n or other html codes saved.
I need to save the textarea line breaks into the database for the result json string with json parse, has anyone a workaround?
UPDATE1
The JSON Result is only a snipped. Here is the full json result it's works perfect if the profile_description has NO line breaks
{"_id":"XYZ","business_id":"7XYZ","banner_url":"XYZ","__v":0,"profile_description":"My name is example
My name is example"}
Json line which created this error
"My name is example
My name is example"}
That is not valid JSON to begin with.
In JavaScript, a text literal delimited by single or double quotes, can not contain an actual line break. It would either need an \ at the end of every line, or the line breaks would need to be replaced with the characters \n inside the text literal.
It is important to always properly differentiate between data, and code.
When you read the field value using $(this).val(), the result is data. In there, you have an actual line break, hexadecimal byte value 0A.
But JSON is code, it needs to get parsed. So it has to follow the basic syntax rules for text literals, that JavaScript imposes.
So those line breaks would need to be replaced by the characters \n, which can be done simply by
someVariableContainingText = someVariableContainingText.replace(/\n/g, "\\n")
That would get you "My name is example\nMy name is example" here, and that now is a valid JS text literal. As soon as your JSON contains that, instead of an actual line break, it can be parsed properly.

SyntaxError: unterminated string literal in PHP variable

I search through the numerous questions already asked about the "unterminated string literal" syntax error but found nothing helping me ...
So, I have this Javascript function :
function parametresModal($parametres) {
document.getElementById('remodalTest').innerHTML = $parametres;
};
Then I call this function on a link in my page :
<a href="#" onClick='parametresModal("<?php the_field('description-defi'); ?>");'>TEST</a>
The parameter written here is simplified ; I actually want to add this Wordpress ACF's function among others and HTML markup, but I found the issue was appearing with this particular field (see below).
This "parametresModal" function is supposed to fill the following div with its parameters :
<div id="remodalTest">MyDiv</div>
Problem is the console outputs
"SyntaxError: unterminated string literal"
The Wordpress ACF's field "description-defi" contains a few lines of text with some simple quotes (ex. c'est, l'éviter, ...).
So I tried to escape the quotes with several methods :
$myField = the_field('description-defi');
$myEscape = json_encode($myField);
or
$myField = the_field('description-defi');
$myEscape = addshlashes($myField);
or
$myField = the_field('description-defi');
$myEscape = htmlspecialchars($myField);
Always resulting in the same error.
Do you see where I could be wrong in my code or my way of thinking the thing ?
Thank you very much !
the_field() will output the content of the selected field. If you want to work with a field, you should use get_field() instead.
See: https://www.advancedcustomfields.com/resources/the_field/
Also the newline character will not be escaped by any of PHP's escape functions, if your String contains newlines, you will need to escape them manually using something like this: $myField = str_replace(array("\r\n", "\n"), "<br>", $myField);.
If you know that your DB will consistently use the same newline sequence, you can replace array("\r\n", "\n") by that newline sequence instead.

Cannot use server side variable in JavaScript due to Unexpected Token ILLEGAL

Our web application allows the user to submit rich text (with some whitelisted HTML tags) to our server. The client-side form uses CKEDITOR to capture the rich text.
Once the user submits their input, I need to retrieve the rich text on a separate page for rendering. The render has to happen dynamically. On document ready, I pull the server side value, create a div element, and dump the rich text into the innerHTML attribute of the div.
i.e. :
var container = document.createElement('div');
div.innerHTML = '{!server_side_value}'; // String interpolation to retrieve the user's input
The problem that the server-side rich text is stored with newline characters. When I attempt to assign the innerHTML attribute, I get the "Unexpected token ILLEGAL" error. I cannot assign the string to innerHTML, nor can I pass it as an argument to a function that strips the new line characters using RegEx. Both attempts result in the 'Unexpected Token' error.
My question is: is it impossible to massage the rich text value in JavaScript because it has new line characters? I am working on a 3rd party platform, so the details of how user input is stored are somewhat hidden in a black box. However, I think I can add a hook to pre-process the data before save. In either case, I am just curious what to do in JavaScript if the server-side string returned with newline characters.
EDIT:
Here is the highlighted line in the console. The reason why I thought it had to do with the newline was because of the space between the first 'p' tag and starting of the second. I know JavaScript multiline strings must use the + operator for concatenation. Another SO user had a similar issue: Javascript: Unexpected Token ILLEGAL Error with appendChild()
var richText = '<p class="p1"><span class="s1">Here is some text.</span></p>
<p class="p1"><span class="s1">Here is some more text</span><br><br></p>';
If you're stuffing that exact thing into a js var then, yes it will care about the line feed. If you are getting it from the server via javascript, it shouldn't be an issue.
Since you didn't specify your server side language, I'll use an example with C#/Razor/MVC
var richText = '#RichText' // this is going to fail
At this point, I would do #RichText.Replace("\r\n","") or something
Your regex function fails because it's still the server side variable that contains line breaks.

JS - JSON.parse - preserve special characters

I'm running a NodeJS app that gets certain posts from an API.
When trying to JSON.parse with special characters in, the JSON.parse would fail.
Special characters can be just any other language, emojis etc.
Parsing works fine when posts don't have special characters.
I need to preserve all of the text, I can't just ignore those characters since I need to handle every possible language.
I'm getting the following error:
"Unexpected token �"
Example of a text i'm supposed to be able to handle:
"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"
How can I properly parse such a text?
Thanks
You have misdiagnosed your problem, it has nothing to do with that character.
Your code contains an unescaped " immediately before the special character you think is causing the problem. The early " is prematurely terminating the string.
If you insert a backslash to escape the ", your string can be parsed as JSON just fine:
x = '{"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦\\"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}';
console.log(JSON.parse(x));
You need to pass a string not as an object.
Example
JSON.parse('{"summary" : "a"}');
In your case it should be like this
JSON.parse(
'{"summary" : "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}')

How to avoid the exception "Invalid hex characters in a String"

I'm using Javascript and Rhino (to do some Java codes). I want to execute the following code.
service.push(deviceToken,payload);
As the first string contains 'x' it gives the following exception.
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.WrappedException: Wrapped java.lang.RuntimeException: Invalid hex character: x
That string has to be there as it is. Therefore no replaces are possible.
I'm using Java-apns and I use this method to push notifications with the device token and the payload.
Your device token should contain only hexadecimal characters 0–9 , A, B, C, D, E, F (or alternatively a–f)

Categories

Resources