2

I am trying to copy the string

 $str = '
         this
         is
         my
         string';

to a JavaScript variable like so

 var str1 = '<?php echo $str ?>';

but when I do, I get an error

Uncaught SyntaxError: Unexpected token ILLEGAL

If you are asking yourself why I'm doing this, I create a <table> with PHP and insert it to the $str variable and want to later use it in a JavaScript function.

1
  • Whenever, you need to place a string available in a PHP variable in a JavaScript code generated by the PHP, you should use json_encode() function. For your example: var str1 = <?php echo json_encode($str) ?>; Commented Jan 24, 2012 at 20:51

5 Answers 5

5

You should just use json_encode() from http://www.php.net/manual/en/function.json-encode.php

Example:

var str1 = <?php echo json_encode($str) ?>;

It takes care of converting newlines to \n, escaping any other special characters as necessary, preserve spaces, etc.

Example output for your string:

var str1 = "\n         this\n         is\n         my\n         string";
Sign up to request clarification or add additional context in comments.

Comments

0

Problem is EOL character in your PHP strng.

Use it like this (after replacing all EOL characters with a space):

var str1 = '<?php echo str_replace("\n", " ", $str) ?>';

Comments

0

Javascript does not except multiline strings. You can put a backslash before the end of each line if you want to keep it looking like that.

Comments

0

JavaScript doesn't like multiline string literals or have a here-doc syntax. Try changing your string to

$str = ' \
         this \
         is \
         my \
         string';

Comments

-1

Have you tried this?

var str1 = '<?php echo $str; ?>';

Notice the semicolon.

2 Comments

Semicolon is not necessary there.
What will happen if $str = "'fail'" ?

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.