0

I want to push a php variable to javascript. The code is below but does not seem to work. Can anyone show me how to do this?

ticks.push(<?php echo json_encode($new); ?>);
3
  • 2
    What does the echo json_encode($new); produce? What's the resulting line of javascript? Commented May 15, 2015 at 6:10
  • Also, does json_last_error() return anything? Commented May 15, 2015 at 6:15
  • i want to add the string present in $new to next element of tick array Commented May 15, 2015 at 6:15

3 Answers 3

2

Is this what you're looking for?

ticks.push(JSON.parse('<?= json_encode($new); ?>'));

Or broken down:

var json = '<?= json_encode($new); ?>';
var obj = JSON.parse(json);
ticks.push(obj)

also addressed in this issue:

Accessing an array in PHP from Javascript/jQuery

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

Comments

-1

can you try this

var tricks = [
<?php 
    foreach ($new as $n) {
        echo '"'.$n'", ';
    }
?>
];

1 Comment

There's so much "wrong" with your suggestion, that I just don't know where to start from...
-2

you can use websocket to do such like functionality; in it you can send the result back to the client from the php code when it is ready one good example on that is how stackoverflow notify you when there is new question, or when they notify you if the post is edited.

Comments

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.