1

I know this may sound similar to some past Q/As, I think mine is slightly different though.. I have a webpage which I want to dynamically load text file information. I upload the text file through an iframe and I want to save this information from php to Javascript. Whenever I try to save this as a regular variable it doesn't work so I have tried to do this by saving this information as a part of the $_POST array under a hidden form named $_POST['hidden_form']. Whenever I try to read the php into Javascript, I keep getting an error "Unexpected token ILLEGAL." I have tried the following two codes:

for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
  echo "saved_form[$i]='" . $_POST['hidden_form'][$i]. "';\n";
}

and saved_form = <?php echo json_encode($_POST['hidden_form']); ?>;

Assigning a php array into a javascript array

I think the error has to do with the " ' " needed to specify the array but not sure. I have no idea where to go from here so any help would be GREATLY appreciated. If there are better methods to do this please let me know. Thanks in advance!

Community
  • 1
  • 1
user839260
  • 17
  • 4

2 Answers2

0
saved_form = '<?php echo addslashes(json_encode($_POST['hidden_form'])); ?>';

Or

for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
  echo "saved_form[$i]='" . addslashes($_POST['hidden_form'][$i]) . "';\n";
}

Both should work, probably had quotes breaking something?

Lee
  • 10,496
  • 4
  • 37
  • 45
  • The first one won't work, because `json_encode` already wraps quotes around whatever is needed. – Niet the Dark Absol Jun 11 '12 at 15:42
  • It will, it just needs to be passed into a parser (i.e. parseJSON in JQ). My bad though, im used to async loading rather than printing into the document – Lee Jun 12 '12 at 09:01
0

the best way i have used is,

text/javascript

var saved_form = <?php echo json_encode($_POST['hidden_form']) ?>

Please note there are no Quotes around the php so your saved_form is an Object not a string json string witch would require you to to use var form_object = eval(saved_form)

@Lee might have meant this?

Just a note though i would not use the Raw $_POST pass it to a function that can loop though and addSlashes every value inside the post some thing like

<?php
function arr_addSlashes($array){
    $ret = array();
    foreach($array as $k => $v){
        $ret[$k] = addSlashes($v);
    }
    return $ret;
}
?>
HotHeadMartin
  • 260
  • 2
  • 10