0

PHP function addslashes allows me to escape single quotes, newlines, etc. The problem is that I can't make an actual new line in the alert box. I tried replacing backslash n by double backslash n but it will display literaly "\n" in my alert box.

<?php $this->info = "Hello ' world\nNew line"; ?>

<script type="text/javascript">
    $(document).ready(function() {
        alert('<?php echo addslashes($this->info); ?>');
    });
</script>
Matthew
  • 10,498
  • 8
  • 53
  • 66

2 Answers2

6

Use json_encode to create a valid JS string:

<script>
    alert(<?php echo json_encode($this->info); ?>);
</script>
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
2

try this

   <script>
    var myvar = <?php echo json_encode($this->info); ?>;
    alert(myvar);
  </script>
thumber nirmal
  • 1,629
  • 3
  • 16
  • 27