1

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

how does it know to look at woepanel.php to get $vars from it tho?
Is your third code sample a separate script? I thought it was in the same script as the second.
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
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.
could i read it in from the text file php creates with my array in it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.