lvil
lvil

Reputation: 4336

Passing special characters from php to javascript

I am passing a string variable from php to javascript.
The string contains " But javascript doesn't get it.
How can I escape this character?

UPD:
To be more clear, first I don't want to make many changes in the code (not written by me)...
The string is passed this way:

var string = '<? echo $string;?>' ;

Single quotes are used. Maybe there is a way to change smth. in the string itself?

Upvotes: 2

Views: 5478

Answers (3)

Microfed
Microfed

Reputation: 2890

Use urlencode() function in php code to pass the string to javascript code and decodeuri() in javascript to decode that string.

Upvotes: 0

Quentin
Quentin

Reputation: 944441

Assuming a string delimited using double quotes, add_slashes will do the job in the particular case.

Wrapping the data in an associative array, running it through json_encode and altering the JS to expect the changed data structure is a safer approach though (since that will take care of other characters which are significant, such as literal new lines).

(Technically speaking, with the current implementation of json_encode you could skip wrapping it in an associative array … but a plain string isn't valid JSON and I'm inclined to avoid depending on a function that is supposed to generate JSON not throwing an exception when given a data structure that can't be turned into JSON).

If you are embedding the script in an HTML document you will also have to take steps to ensure that the resulting JS doesn't contain any HTML that could cause issues (such as " in an script included as an attribute value).

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could use the json_encode method:

<script type="text/javascript">
    var value = <?php echo json_encode($someValue); ?>;
    alert(value);
</script>

Upvotes: 3

Related Questions