Reputation: 181
Teaching myself the flow of data from mySQL -> PHP -> JSON / Javascript and kind of stuck at this point. All I want to do is iterate through the external JSON data and put them into an unordered list. Ive tried to edit the example given on the jQuery site to work for me but I cant figure it out. Any help is appreciated. Here is my code.
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$.getJSON('links.json', function(json) {
// alert("JSON Data: " + json[1].pagetitle);
});
I can confirm that data is being pulled from the external JSON file by using that commented out alert.
Here is my code for creating the JSON file:
// Require Database Connection
require_once "pdo_testdb_connect.php";
// Query Database for all available links
$STH = $dbh->query('SELECT pagetitle, pagelink FROM links');
// If empty..
if ($STH == '') {
echo "There are no links available at this time.";
}
// Set Fetch Mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
$allLinks = array();
// Pull all page titles and links
while($row = $STH->fetch()) {
$allLinks[] = $row;
}
// Encode array to JSON
$je = json_encode($allLinks);
// Write to file
$fp = fopen('links.json', 'w');
fwrite($fp, $je);
fclose($fp);
Upvotes: 0
Views: 1030
Reputation: 126
I hope this code will work for you
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$.getJSON('links.json', function(json) {
// alert("JSON Data: " + json[1].pagetitle);
$.each(json, function(i,val){
var li_populate = "<li>"+i+"+ val +"</li>";
$("#myul").append(li_populate);
})
});
Upvotes: 2