ItsKasper
ItsKasper

Reputation: 35

PHP in javascript in PHP

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

Upvotes: -1

Views: 76

Answers (4)

Amine programmeur
Amine programmeur

Reputation: 1

Test this:

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

It's work!

Upvotes: 0

Ryan Tuosto
Ryan Tuosto

Reputation: 1951

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>";

Upvotes: 0

ItsKasper
ItsKasper

Reputation: 35

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!

Upvotes: 0

siddiq
siddiq

Reputation: 1711

This should work

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

Upvotes: 1

Related Questions