Brian
Brian

Reputation: 5028

How to show print_r() content in alert message box?

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.

Upvotes: 2

Views: 18383

Answers (1)

Danijel
Danijel

Reputation: 12709

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>';
    }
    

Upvotes: 6

Related Questions