1

I need to add a break in the javascript with the below situation.

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \n";
}
if(isset($case2)){
    $str_alert .= "have case2 \n";
}
if(isset($case3)){
    $str_alert .= "have case3 \n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>

it break the javascript code and shows the error

SyntaxError: unterminated string literal

please give me any solution

Sathish Kumar D
  • 274
  • 6
  • 20

3 Answers3

1

Add \ to escape \n in php. Try following code

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \\n";
}
if(isset($case2)){
    $str_alert .= "have case2 \\n";
}
if(isset($case3)){
    $str_alert .= "have case3 \\n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>
B. Desai
  • 16,414
  • 5
  • 26
  • 47
1

You need to represent characters that are not allowed as literals in JS strings (like new lines) by escape characters.

Since JSON is a data format based on a subject of JavaScript's literal syntax, you can use PHP's json_encode function to convert any basic data type (string, number, array, associative array) into JavaScript code with all the correct escape characters.

By default it will even escape / so you can safely output the string </script>.

alert(<?=json_encode($str_alert);?>);

Since the " will be included in the JSON, you should not add them manually.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Javascript strings can't break across newlines without an escape (). See this question for detailed answers:

How do I break a string across more than one line of code in JavaScript?

l.g.karolos
  • 1,131
  • 1
  • 10
  • 25