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,988
  • 11
  • 54
  • 69

2 Answers2

6

Use json_encode to create a valid JS string:

<script>
    alert(<?php echo json_encode($this->info); ?>);
</script>
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

try this

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