1

I have a variable in my MySQL database. I want this variable to handle both simple and double quotes.

For example:

$variable = "I'm happy" or $variable = I'm happy or  $variable = "I am happy"

In my DB, the first example is this: "i'm happy" and that works for me. The problem is now on my JS function because I want to call my data:

nameFolder = "<?php echo $variable ; ?>"

But, if $variable = "I'm happy", I've got double "" so I get a JS error. And if I put single quote, the problem is the same with another case.

Any ideas?

pilsetnieks
  • 10,225
  • 12
  • 47
  • 60
Kaherdin
  • 1,825
  • 3
  • 19
  • 29

2 Answers2

5

The best way to echo data to JavaScript is to use json_encode:

var nameFolder = <?php echo json_encode($variable); ?>;

N.B.: There shouldn't be any surrounding quotes, function will handle that for you.

VisioN
  • 138,460
  • 30
  • 271
  • 271
1

Use

nameFolder = "<?php echo str_replace('"', '\"', $variable); ?>"
str
  • 38,402
  • 15
  • 99
  • 123