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,330
  • 12
  • 48
  • 60
Kaherdin
  • 2,055
  • 3
  • 23
  • 34

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
  • 143,310
  • 32
  • 282
  • 281
1

Use

nameFolder = "<?php echo str_replace('"', '\"', $variable); ?>"
str
  • 42,689
  • 17
  • 109
  • 127