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

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.