passing PHP string to JavaScript: unterminated string literal

ajax, javascript, php

Solution

Your JS code:

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

Will give Javascript syntax error if one or more of your PHP variables `$values1` OR `$values2` contain single quote `'` in them.

Make sure your PHP variable don't contain single quotes in them by replacing all single quotes to something else otherwise use double quotes `"` to create JS var like this:

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

Provided PHP variables don't contain double quotes.

Problem

i am assigning PHP var to my javascript var and sending to PHP file through ajax-jQuery, but my php variable contains newline chars which i have replaced with `<br>` ``` e.g. $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 post data to PHP file but when i print this data on console it is giving me error- SyntaxError: unterminated string literal. Can anyone help ?

Original source