I need to convert my php array into a javascript variable. I am using json_encode to do this but it is returning with some errors. I have a php variable:
<?php $damage_array = $listing->tire_detail->damage_details; ?>
which prints out to be
Array ( [lf] => 4 [rf] => 9 [lrfo] => 22 [rrfo] => 19 [lrfi] => 22 [rrfi] => 19 [lrro] => 15 [rrro] => 10 [lrri] => 15 [rrri] => 10 )
Then in my javascript I have:
var damages = "<?php echo json_encode($damage_array); ?>";
which prints out to:
var damages = "{"lf":4,"rf":9,"lrfo":22,"rrfo":19,"lrfi":22,"rrfi":19,"lrro":15,"rrro":10,"lrri":15,"rrri":10}";
Can someone please help me clean this out so that my js variable is an actual array?
asked Dec 17, 2015 at 19:56
JordanBarber
2,0916 gold badges37 silver badges67 bronze badges
2 Answers 2
try this:
var damagesAsString = '<?php echo json_encode($damage_array); ?>'; // json string
var damages = JSON.parse(damagesAsString); // json object
answered Dec 17, 2015 at 19:57
madox2
52.3k21 gold badges106 silver badges101 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
JordanBarber
The one you posted before this one worked better, it returns {"lf":4,"rf":9,"lrfo":22,"rrfo":19,"lrfi":22,"rrfi":19,"lrro":15,"rrro":10,"lrri":15,"rrri":10}, why did you change?
madox2
JSON.parse() parses string to json object. Do you want string or object as result?
I think you can just do this...
var damages = <?php echo json_encode($damage_array); ?>;
answered Dec 17, 2015 at 20:28
geggleto
2,6251 gold badge18 silver badges18 bronze badges
Comments
Explore related questions
See similar questions with these tags.
default
<?php echo "var damages = ".json_encode($damage_array); ?>;