0

First off, my apologies if this is already addressed in another post - I'm sure it is, but I have not been able to figure it out.

Second, I have a PHP page that outputs an array in a JSON format like this:

[{
   "chemical":"Corrosion_Inhibitor",
   "TargetDose":81,
   "AppliedDose":26,
   "ppbbl":"$0.97"
},
{
   "chemical":"Scale_Inhibitor",
   "TargetDose":56,
   "AppliedDose":63,
   "ppbbl":"$1.00"
},
{
   "chemical":"Biocide",
   "TargetDose":55,
   "AppliedDose":55,
   "ppbbl":"$0.30"
},
{
   "chemical":"Friction_Reducer",
   "TargetDose":23,
   "AppliedDose":44,
   "ppbbl":"$0.42"
}] 

I would like to pass that array to a variable tableData in JavaScript so that I can populate a table on another PHP page. Any guidance would be greatly appreciated. Clearly I am not an expert in either of these languages.

Amous
  • 534
  • 5
  • 18
b.roberts
  • 1
  • 1
  • I'm not sure if I interpreted this correctly. Essentially you want to pass data from one PHP file to another? – Amous Apr 23 '16 at 01:44
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Serge Seredenko Apr 23 '16 at 01:53
  • Are you requesting the PHP page with straight HTTP (e.g. a link or form submit from HTML) or with AJAX. – pgraham Apr 23 '16 at 01:58

2 Answers2

0

Sounds like you want to dynamically generate a table from a JSON response? If you are sending a request to the php script that outputs that JSON response, you can use JSON.parse(responseData) to parse the JSON string response to a JS variable array/array of objects.

Talha
  • 807
  • 9
  • 13
0

This is a basic way to do that:

<?php 

$dataFromPHP =
'[{
   "chemical":"Corrosion_Inhibitor",
   "TargetDose":81,
   "AppliedDose":26,
   "ppbbl":"$0.97"
},
{
   "chemical":"Scale_Inhibitor",
   "TargetDose":56,
   "AppliedDose":63,
   "ppbbl":"$1.00"
},
{
   "chemical":"Biocide",
   "TargetDose":55,
   "AppliedDose":55,
   "ppbbl":"$0.30"
},
{
   "chemical":"Friction_Reducer",
   "TargetDose":23,
   "AppliedDose":44,
   "ppbbl":"$0.42"
}] 
';
?>
<html>
   <body>
       <!-- main HTML content -->
   </body>

   <script>
     var tableData = <?php echo $dataFromPHP ?>;

      // do whatever you want with that data
   </script>
</html>
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • thanks BizzyBob - now how would I assign that json array to $dataFromPHP if the json array was echoed in a separate .php file? In other words, I'm trying to write a script that dynamically creates a table on a dashboard page from a json output generated on a separate .php page. – b.roberts Apr 24 '16 at 14:39
  • How/when are you telling that other page to do the work? If the user is changing pages, you could store in session variable. – BizzyBob Apr 24 '16 at 16:04