I have a bookmarks page where images are displayed. The images are being displayed fine however above the images, the array which the images are retrieved from is also displayed such as:
[["1", "img/exampleImage1.png"], ["2", "img/exampleImage2.png"]]
This is the bookmarks page
<?php include 'retrieveSymbol.php';?>
<div id="bookmarkedSymbols"></div>
<script>
//populates product container
$.getJSON("retrieveSymbol.php", function(data){ //retrieves json array
$.each(data, function(i, field){ //loops through array
$("#bookmarkedSymbols").append(
//creates product box filling it with data
"<img src='" + field[1] + "'" + "id='symbol' alt='stadium'></a>"
);
});
});
</script>
This is the retrieve symbol page :
<?php
//connect to the database
$mysqli = NEW MySQLi ('localhost','root','','bookmarkedSymbols');
//query database
$resultSet = $mysqli->query("SELECT * FROM symbols");
//count the rows
if($resultSet->num_rows != 0) {
//turn the results into an array
$rows = $resultSet->fetch_all();
echo json_encode($rows);
}else{
echo "{no connection}";
}
?>
In the page with the JS, you don't need to include retrieveSymbol.php
since you are calling it with AJAX.
Remove this:
<?php include 'retrieveSymbol.php';?>
When you include the php script it is echoing the JSON directly on the page.
Avoid including PHP Script explicitly again in the same PHP File. because this will get triggered through JavaScript asynchronously !
Try like below.
<div id="bookmarkedSymbols"></div>
<script type="text/javascript">
//populates product container
$.getJSON("retrieveSymbol.php", function(data){ //retrieves json array
$.each(data, function(i, field){ //loops through array
$("#bookmarkedSymbols").append(
//creates product box filling it with data
"<img src='" + field[1] + "'" + "id='symbol' alt='stadium'></a>"
);
});
});
</script>
You can add document.ready function for this code like below.
$( document ).ready(function() {
console.log( "ready!" );
});
OR like below.
$(function() {
console.log( "ready!" );
});
Your retrieveSymbol.php
code else case has invalid json and add JSON Content Header
, correct like below.
<?php
//connect to the database
$mysqli = NEW MySQLi ('localhost','root','','bookmarkedSymbols');
//query database
$resultSet = $mysqli->query("SELECT * FROM symbols");
//count the rows
header('Content-Type: application/json');
if($resultSet->num_rows != 0) {
//turn the results into an array
$rows = $resultSet->fetch_all();
echo json_encode($rows);
}else{
echo '{"msg": "no connection"}';
}
?>