Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 17978  / 11 Years ago, wed, may 15, 2013, 12:00:00

I know that whenever I write



$food = array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat');
$text = print_r($food, true);
echo $text;


Output will be:




Array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat')




But when I am trying to display this via alert message box, it does not show anything.

The code for js alert I wrote as follows:



echo <script type='text/javascript'> alert('{$text}') </script>; 


This does not work. When I assign a different string to $text then it works. Seems like alert() does not like the format of $test string. If I write in this way:



echo <script type='text/javascript'> alert('Array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat')') </script>;


I get the correct output. So not sure what is wrong there.


More From » php

 Answers
7

To convert PHP array into javascript array you must use json_encode. JSON (JavaScript Object Notation) is a format for data-interchange between programming languages based on the JavaScript. Because JSON is a text format, the result of encoding can be used as a string or as a javascript object.



$food = array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat');

// show the array as string representation of javascript object
echo <script type='text/javascript'> alert('.json_encode($food).') </script>;

// show the array as javascript object
echo <script type='text/javascript'> alert(.json_encode($food).) </script>;

// show the output of print_r function as a string
$text = print_r($food, true);
echo <script type='text/javascript'> alert(.json_encode($text).) </script>;


A few tips for debugging:




  • for inspection of JavaScript objects, console.log is a very useful

  • if you want a cleaner print_r output ( on Windows) use:



    function print_r2($val){
    echo '<pre>'.print_r($val, true).'</pre>';
    }


[#78211] Tuesday, May 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braeden

Total Points: 231
Total Questions: 96
Total Answers: 86

Location: Somalia
Member since Mon, Dec 28, 2020
3 Years ago
;