I'm working on a code where the user can fetch user posts in a list of post titles. If the user clicks on a post title then there should show up a new div box with more information. The posts are fetched with php and the post description will fetched by AJAX. (later i will fetch the posts also with AJAX)
My Problem: Only the first post title works and by clicking it, all post description show up in 1 div box. I think I need an array, and was trying it with no success.
What It Should Do: For example by clicking on title: 2, only the description of post 2 should show up.
And remember, the post title list is dynamic and are fetched data from database.
Here is my code:
INDEX.PHP
<!DOCTYPE html>
<html>
<head>
<title>XY</title>
<meta charset="UTF-8"/>
</head>
<body>
<?php
$db = mysqli_connect("localhost", "root", "", "xy");
$result = mysqli_query($db, "SELECT * FROM images");
while ($row = mysqli_fetch_array($result))
{
echo "<div class='img_title'><button id='img_descr'><a>Title: <b>".$row['img_title']."</b></a></button></div>";
}
?>
<div id="descrs"></div>
<script>
document.getElementById('img_descr').addEventListener('click', loadDescr);
function loadDescr(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'ajax.php', true);
xhr.onload = function(){
if(this.status == 200){
var descrs = JSON.parse(this.responseText);
var output = '';
for(var i in descrs){
output += '<ul>' +
'<li class="ajax_img_descr">ID: '+descrs[i].img_descr+'</li>' +
'</ul>';
}
document.getElementById('descrs').innerHTML = output;
}
}
xhr.send();
}
</script>
</body>
</html>
AJAX.PHP
<?php
// Create Connection
$conn = mysqli_connect('localhost', 'root', '', 'xy');
$query = 'SELECT * FROM images';
// Get Result
$result = mysqli_query($conn, $query);
// Fetch Data
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($users);
?>
Database Structure/Content:
- Create a database called "xy"
Create a table called "images":
CREATE TABLE images ( img_id int(11) not null AUTO_INCREMENT PRIMARY KEY, img_file varchar(250) not null, img_title text(50) not null, img_descr varchar(250) not null );Insert data to database:
INSERT INTO images (img_title, img_descr) VALUES ('Golden Retriever', 'UK:DFYDFBAERSDFBYDFBYDFydfbydfBaeydfb1311y'); INSERT INTO images (img_title, img_descr) VALUES ('Appenzeller Sennenhund', 'Swiss:erydfydfbrehaydydfbydfydbaerydf2ydfb'); INSERT INTO images (img_title, img_descr) VALUES ('German Shepard', 'Germany:ydf3d1fby3df1by3dfb6ydfb31ydf31ydf'); INSERT INTO images (img_title, img_descr) VALUES ('Alaskan Klee Kai', 'USA:f3ngxfgxfgnxfxfgnxfg3xf31gnxfgner6ae13')