将php变量分配给javascript变量后,两个单词之间的空格会丢失

I have created two simple files in php.

first file (i.e. input.php ):

  • Created one form having one textbox and one submit button
  • I have one textbox, user will add input in this textbox
  • One submit button, after clicking on this form will get submit ( used post method )

Second file (process.php) :

  • Posted contents are received here.
  • Assigning textbox ( from $_POST supergloble variable ) value to javascript variable.
  • And displaying this javascript value

What I observed after submitting below content in first file

Input :

Hi this is test
Hello world

After displaying value using javascript value I am getting below content

Output :

 Hi this is testHello world.

the 'test' and 'Hello' words are getting concatenated.

below is my code from process.php :

    <script type="text/javascript">

    var display = <?php echo $_POST['textareaInput']; ?>
    alert(display);

    </script>

I wanted to know whether assignment of php variable to javascript variable is right ?

Can anybody please let me know, what is the root cause here ?

Thanks in advance

You're trying to assign a string to a variable, so you should mark it as a proper string:

<script type="text/javascript">

var display = "<?php echo addslashes($_POST['textareaInput']); ?>";
alert(display);

</script>

Try this:

var display = "<?php echo addslashes($_POST['textareaInput']); ?>";

you have to replace the line-breaks, here is what you can do (handling also the quotes if there are some) :

 $input = preg_replace("/?
/", "\
", addslashes($_POST['textareaInput']));