-1

I want to call a javascript function from my PHP code. I have achieved this by using:

echo '<script type="text/javascript"> drawChart($id); </script>';

This works fine, but I want to get data from my PHP code, which I did using the following:

var t_array = ?php echo json_encode($t_array); ?>;

(Yes, I know there's a > missing.) I think the PHP closing tag is interfering with the rest of the code. So now my question: How can I get PHP data without using the PHP tags?

Thanks in advance

7
  • Yes, I know there's a > missing So why don't you fix that first? Commented May 2, 2017 at 15:13
  • AJAX is what I'm thinking of, but I think there are more efficient way. Commented May 2, 2017 at 15:13
  • where did u declared $t_array? Commented May 2, 2017 at 15:14
  • 1
    drawChart($id); will be exactly that, because that string is in single-quotes - so it won't be passed as a variable. And there's a < missing in front of what should be <?php. And that's exactly how you get it, there's no need for AJAX unless you need it dynamically without reloading the website of the PHP values changes. Commented May 2, 2017 at 15:14
  • 1
    Just var t_array = JSON.parse(<?php echo json_encode($t_array);?>) should work fine. Use ParseJson function. Commented May 2, 2017 at 15:15

4 Answers 4

1

This should work

var t_array = <?php echo json_encode($t_array);?>;
Sign up to request clarification or add additional context in comments.

1 Comment

Anyway the result of json_encode is a string in php. So I always use Json Parse. Why not suggesting a good practice :)
0

Unfortunately, none of the given answers worked. What I did was adding arguments to the javascript function and declare the value in the echo. That way, I could just the PHP variables directly. Make sure you use json_encode first!

Comments

0

You just need to concatenate your string properly:

// Use double quotation marks so variables can be evaluated in the string
echo "<script type='text/javascript'>" . 
         "var t_array = JSON.parse(" . json_encode($t_array) . ");" .
         "drawChart($id);" . 
     "</script>";

Comments

0

Test this:

echo "<script type='text/javascript'> drawChart(" . $id . "); </script>";

It's work!

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.