Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i'm trying to update an array called "vars" on a page from an array stored on a php page

i got one page sending an array

var jsonString = JSON.stringify(vars);
$.ajax({
    type: "POST",
    url: "woepanel.php",
    data: {data : jsonString}, 
    cache: false,

    success: function(){
        $('#sent').attr("bgcolor", "#00FF00");
        $('#notsent').attr("bgcolor", "#FFFFFF");
    }

php receiving it and writing to a file

<?php
$vars=json_decode($_POST['data']); 
?>
<?php echo $vars ?>
<?php
file_put_contents('vars.txt', print_r($vars, true));
?>

and that part all works

then i need php to pass it to another page so in php i have

<?php
$varjava = '["' . implode('", "', $vars) . '"]';
?>

then in javascript i have

<script type="text/javascript">
function test() {
   var vars = <?php echo $varjava ?>;
   alert (vars);
};
</script>
share|improve this question

1 Answer 1

up vote 1 down vote accepted

Just encode it once again in JSON directly:

function test() {
   var vars = <?php echo json_encode($vars) ?>;
   alert (vars);
};

JSON is valid JavaScript when assigned to a variable or passed to a function.

share|improve this answer
    
how does it know to look at woepanel.php to get $vars from it tho? –  user1547167 Apr 15 at 19:46
    
Is your third code sample a separate script? I thought it was in the same script as the second. –  MrCode Apr 15 at 19:48
    
all the php is on a separate page, the first code sample is on page a, all the php is on "woepanel.php" and the 4th sample is on page b if that helps –  user1547167 Apr 15 at 19:50
    
If the 4th is a new page then it can't have access to the $vars unless you store it somewhere such as the session or on disk. –  MrCode Apr 15 at 19:55
    
could i read it in from the text file php creates with my array in it? –  user1547167 Apr 15 at 20:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.