...

View Full Version : display php array in javascript alert



aprestong
03-14-2007, 02:46 PM
Hi everyone -


<form>
<input type="button" onclick=
"alert('<?php print_r($_SESSION);?>')"
value="Debug">
</form>


This doesn't work - and I suspect it has something to do with newlines and JavaScript string literals - but I've been unsuccessful.

I figured since it probably requires some formatting (preg_replace or something) with php that I should post it in the php forum instead of the JS forum.

Anyone have any tips?

timgolding
03-14-2007, 03:06 PM
try



<?PHP
echo '<form>
<input type="button" onclick=
"alert(\''.(print_r($_SESSION)).'\')"
value="Debug">
</form>';
?>

aprestong
03-14-2007, 03:15 PM
Thanks for the help, timgolding -
I tried this, but it just prints the array above the button.

timgolding
03-14-2007, 03:36 PM
Yeah I just noticed :( two secs

timgolding
03-14-2007, 03:37 PM
This outputs all the values but not the key



<?PHP
$_SESSION['test']=test;
$string=implode('',$_SESSION);

echo '<form>
<input type="button" onclick=
"alert(\''.($string).'\')"
value="Debug">
</form>';
?>

aprestong
03-14-2007, 03:42 PM
Thanks for your help -

I guess I was just looking for an easy way to view my entire session array for debugging while working on this project - I thought a JS alert box would be nice, but I'd really like it to look like a nicely formatted array.

Is there a better way, perhaps?

timgolding
03-14-2007, 03:45 PM
This looks not so bad. However im sure there will be a funtion that formats the array into a readable string without echoing it to the screen.



<?PHP
$_SESSION['test']='test1';
$keys=array_keys($_SESSION);
foreach($keys as $val){
$string.=$val.' => ';
$string.=$_SESSION[$val].', ';
}

echo '<form>
<input type="button" onclick=
"alert(\''.($string).'\')"
value="Debug">
</form>';


?>

aprestong
03-14-2007, 04:47 PM
That actually looks fine - but it doesn't work the nested array I put in my session.

I do appreciate your help, though - please don't worry about taking the time to fix this if you are busy with other things... It isn't necessary by any means... just a novelty.

Inigoesdr
03-14-2007, 08:13 PM
If you use print_r($array, 1) the output will be returned as a string so you can echo it where you want instead of printing it at the top of the page(you can use any boolean true value, not just 1). print_r() (http://www.php.net/manual/en/function.print-r.php)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum