2

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?

1
  • hi, can you tell little more details. such as, how your getting the string value in ajax or normal page request. If post your sample code, it may help you to get the result..! Commented Nov 20, 2011 at 9:35

3 Answers 3

3

You could use the json_encode method:

<script type="text/javascript">
    var value = <?php echo json_encode($someValue); ?>;
    alert(value);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

@lvil, instead of var string = '<? echo $string;?>'; you should use var string = <? echo json_encode($string); ?>; as shown in my answer if you want to ensure proper escaping of the string. If you don't want to modify your code I am afraid it will break everytime you have some special character in the string which could potentially break javascript.
0

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).

Comments

0

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

Comments

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.