Fl-0
Fl-0

Reputation: 37

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 !

Upvotes: 1

Views: 2388

Answers (1)

kalsowerus
kalsowerus

Reputation: 1008

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.

Upvotes: 3

Related Questions