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]";
}
?>