Reputation: 925
Ultimate Goal: I want to take data I keep in a MySQL Database and put it into an Array of Arrays in JavaScript, so it can be manipulated client side.
So far, I have been able to pull data from my database with this code:
<?php
...
$num=1;
$q = "SELECT blah1, blah2, blah3 WHERE blah4=$num";
$sth = mysqli_query ($database, $q);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
(from: JSON encode MySQL results)
This is where I am stuck, because I am having trouble getting this data into JavaScript.
One solution I can find is Parsing a Separate PHP Array in Javascript:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
But the problem with this implementation is that it would spit out all of the database content I query onto the source-code of the page. If I have to do this, I might as well skip the database and just keep all of the content in javascript.
I am thinking there must be a way with jQuery/AJAX to pass the value of $num to a PHP script, grab this data and put it into a JavaScript Array without having to output all of it to the page.
Any assistance would be appreciated.
Thank you!
Upvotes: 3
Views: 13359
Reputation: 33349
This solution you posted:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
Is actually a very good approach. Using AJAX is drastically slower (because of network latency).
Unless you really need AJAX for some reason, you should avoid using it. It will add a noticeable split second of load time to the page, often for no benefit at all.
Above all when structuring your page, you want to try and reduce the number of individual network requests between the browser and the server. The less requests the faster your page will be. This is especially true for javascript and ajax, because they are unpredictable and browsers find it very difficult to optimise any part of the page where it's being used.
We're talking about one quarter of a second compared to one millionth of a second, for exactly the same end result.
Upvotes: 7
Reputation: 580
You can also do this without AJAX
var jsonarray = eval(<?php echo json_encode($array); ?>);
Upvotes: 1
Reputation: 18446
Making an AJAX call with jQuery is easy enough. Take a look at the documentation: http://api.jquery.com/jQuery.get/
Upvotes: 2