PHP string passing in JavaScript: unterminated string literal

I assign PHP var to javascript var and send to the PHP file via ajax-jQuery, but my php variable contains newline characters, which I replaced with <br>

 eg $values1 = 'abc<br>pqr<br>xyz'; $values2 = 'xyz<br>lmn'; javascript - var data = 'val1=<?php echo $values; ?>&val2=<?php echo $values2; ?>'; 

and then ajax script to send data to a PHP file

but when I print this data on the console, it gives me an error. SyntaxError: unterminated string literal.

Can anyone help?

+4
source share
3 answers

Your JS code:

 var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>'; 

Gives a Javascript syntax error if one or more of your PHP variables $values1 OR $values2 contain a single quotation mark in them ' .

Make sure your PHP variable does not contain single quotes in them by replacing all single quotes with something else, otherwise use double quotes " to create JS var as follows:

 var data = "val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>"; 

The provided PHP variables do not contain double quotes.

+2
source

First of all, you have a typo that may cause an error:

 // --------------------------------v var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>'; 

Then I suggest you use an object like data to request an Ajax:

 var data = { val1: '<?php echo $values1; ?>', val2: '<?php echo $values2; ?>' }; 

It is also better to avoid single quotes ' in the variables $values1 and $values2 .

0
source

Try using <br /> instead of <br> . Just guess here without testing.

-1
source

Source: https://habr.com/ru/post/1440015/


All Articles