Reputation: 274
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
Upvotes: 1
Views: 239
Reputation: 943193
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.
Upvotes: 1
Reputation: 16436
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>
Upvotes: 1
Reputation: 1142
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?
Upvotes: 0