Dvir Levy
Dvir Levy

Reputation: 8108

PHP string to JavaScript

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.

Upvotes: 2

Views: 5055

Answers (5)

Susam Pal
Susam Pal

Reputation: 34164

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";

Upvotes: 5

j08691
j08691

Reputation: 207881

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

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

Upvotes: 0

CoffeeRain
CoffeeRain

Reputation: 4522

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.

Upvotes: 0

anubhava
anubhava

Reputation: 784998

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) ?>';

Upvotes: 0

IsisCode
IsisCode

Reputation: 2490

Have you tried this?

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

Notice the semicolon.

Upvotes: -1

Related Questions