1

Have googled a solution for this question for quite some time and it seems a lot of people are asking about the same thing. Haven't found a good answer that works though.

What I want to do: I have a simple database called "fruitStand". It has a single table called "fruitTable" which contains two columns:

**fruit**   **cost**
  apple        5
  pear         4
 banana        2
 orange        6

I can easily fetch the rows with a PHP script and display the result directly on the screen. However, I want to be able to get the result into my javascript arrays so I can build some graphs based on it.

After considering this post, I decided to use Jquery Ajax to glue the HTML/javascript code with the PHP code. I'm using the two files below (index.html and getData.php) along with the database. This generates the following HTML output when I hit the "Get data!" button:

apple5pear4banana2orange6

Now to the actual question: How could I modify the code so I'm able to return the results in js array/object form? I want it to look something like this:

array1 = ["apple", "pear", "banana", "orange"]
array2 = [5,4,2,6]

The ultimate goal is to use these arrays when plotting the interactive graphs (will later on add buttons to select fruits/cost).

The index.html file:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
   $("#display").click(function() {
     $.ajax({
       type: "GET",
       url: "getData.php",
       dataType: "html",
       success: function(response){
           var store = $("#responsecontainer").html(response);
       }
     });
   });
 });
</script>

<body>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Get data!" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center"></div>
</body>
</html>

The PHP file:

<?php
mysql_select_db('fruitStand',$con);
$result=mysql_query("select * from fruitTable",$con);

$con=mysql_connect("localhost","root","password");
if (!$con){
    die('Could not connect: ' . mysql_error());
}

while($data = mysql_fetch_row($result)){
    echo "$data[0]";
}
?>
Community
  • 1
  • 1
Zooma
  • 73
  • 2
  • 7
  • Have you thought of using Ajax instead? Fetching data directly through PHP makes the size of the embedded script larger, increasing bandwidth usage and loading times. It's easier to just run an Ajax request to an end that returns a JSON value, then you can handle it with an Ajax callback. – CristianHG Apr 26 '16 at 19:15
  • Good point. Yes, I started this off today and am now trying to get this example (Nehas response) to work: http://stackoverflow.com/questions/16707648/using-jquery-ajax-to-retrieve-data-from-mysql – Zooma Apr 26 '16 at 20:07

2 Answers2

2

If I were wanting to share an array of data from php to Javascript, I would use JSON.

Format the array that you want it to be used in php, then use json_encode php method to convert the php array to JSON.

In the js, use JSON.parse to decode the JSON into a Javascript object.

<html>
<head>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
<?php $phpArray = array(); ?>
<?php $phpArray = array(array('fruit' => 'green', 'cost' => 10), array('fruit' => 'blue', 'cost' => 9),array('fruit' => 'red', 'cost' => 8), array('fruit' => 'yello', 'cost' => 7));?>



<script>
    var fruit = [];
    var cost = [];

    var jsString = '<?php echo json_encode($phpArray);?>';
    var jsArray = JSON.parse(jsString);
    for(var i in jsArray){
        fruit[i] = jsArray[i]['fruit'];
        cost[i] = jsArray[i]['cost'];
    }
    console.log(fruit);
    console.log(cost);
</script>

Expected console output:

["green", "blue", "red", "yello"]
[10, 9, 8, 7]
Jake Mroz
  • 51
  • 4
  • Thanks! Will take a look at JSON. Have tried AJAX also and it seems I can get that to work with this example: http://stackoverflow.com/questions/16707648/using-jquery-ajax-to-retrieve-data-from-mysql – Zooma Apr 26 '16 at 19:43
1

this should help you get started. Loop through PHP NOT JAVASCRIPT.

<script>
    <?php

        $i = 0;
        while($row = mysql_fetch_array($result)){
            echo "fruit[$i] = '" . $row['fruit'] . "';";
            echo "cost[$i] = '" . $row['cost'] . "';";
            $i++;
        }
    ?>
    </script>
imvain2
  • 15,480
  • 1
  • 16
  • 21
  • Thanks for responding. I actually managed to do this before. The tricky part is to get the result into js arrays so I can use them when I plot for example pie charts (requires js arrays as input). Any suggestion how I can do this? – Zooma Apr 26 '16 at 17:14
  • if you wrap the code in script tags like my update, is there an error? the echo should echo the js array. – imvain2 Apr 26 '16 at 18:31
  • I get the echo printout, but I don't seem to get the js array. – Zooma Apr 26 '16 at 19:44
  • please update your post with the exact output, thank you – imvain2 Apr 26 '16 at 19:44