1

I have a variable in php

$test = "This is a string
It has multiple lines
there are three total" ;

(Output from a text area)

I want to pass this variable to a javascript function

I have write this in my php file

<?php echo "<script language=javascript>convert('$test');</script>"; ?>

but this makes an error "Unterminated string literal" How can i solve this issue ??

2
  • 1
    not related to your question but you should use <?php echo "<script language=\"javascript\">convert('$test');</script>"; ?> Commented May 3, 2011 at 11:36
  • @Gaurav: <script type="text/javascript"> to be precise Commented May 3, 2011 at 11:37

3 Answers 3

1

Try

$test = "This is a string\nIt has multiple lines\nthere are three total";
Sign up to request clarification or add additional context in comments.

Comments

1
<script>convert(<?php echo json_encode($test); ?>);</script>

1 Comment

It looks like this even escapes double quotes. Very good solution IMO!
0

Try this:

$test = str_replace($test, "\n", "\\n");

4 Comments

It should be \\\n which will turn into backslash followed by newline.
@duri not sure this is true.. we want \n to be passed literally to the JS function.
Oh, I see. I was thinking of another thing (adding backslash to the end of line would allow Javascript string to cross multiple lines; sorry about that).
@duri no sweat, I see what you mean. :-)

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.