0

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

Qirel
  • 25,449
  • 7
  • 45
  • 62
ItsKasper
  • 37
  • 4
  • *Yes, I know there's a > missing* So why don't you fix that first? – Hanky Panky May 02 '17 at 15:13
  • AJAX is what I'm thinking of, but I think there are more efficient way. – RepeaterCreeper May 02 '17 at 15:13
  • where did u declared `$t_array`? – Masivuye Cokile May 02 '17 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 ` – Qirel May 02 '17 at 15:14
  • 1
    Just `var t_array = JSON.parse()` should work fine. Use ParseJson function. – siddiq May 02 '17 at 15:15
  • http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php < this answer seems to be getting some heavy quotage today... – CD001 May 02 '17 at 15:17
  • >Yes, I know there's a > missing So why don't you fix that first? Because it won't show up here >Just var t_array = JSON.parse() should work fine. Use ParseJson function I'll try this. Will get back if it worked! – ItsKasper May 02 '17 at 16:48

4 Answers4

1

This should work

var t_array = <?php echo json_encode($t_array);?>;
siddiq
  • 1,693
  • 3
  • 17
  • 44
  • Anyway the result of json_encode is a string in php. So I always use Json Parse. Why not suggesting a good practice :) – siddiq May 02 '17 at 15:27
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!

ItsKasper
  • 37
  • 4
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>";
Ryan Tuosto
  • 1,941
  • 15
  • 23
0

Test this:

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

It's work!