-
I have a "img_title" list. The 'img_title' getting fetched via php from database - dynamic list.
+------------------------+ | img_title: | +========================+ | golden Retriever | +------------------------+ | Appenzeller Sennenhund | +------------------------+ | German Shepard | +------------------------+ | Alaskan Klee Kai | +------------------------+ | . . . . . | +------------------------+
-
If the user clicks on a "img_title" ...
+-----------------------------+ |<b>Appenzeller Sennenhund</b>| +-----------------------------+
-
... then should show up a new div box with the "img_descr" separately and fetched via AJAX:
+-----------------------------+ +-----------------------------+ | Appenzeller Sennenhund | |<b>Swiss: ABC123... </b>| +-----------------------------+ +-----------------------------+
... or
+-----------------------------+ +-----------------------------+ | golden Retriever | |<b>UK: ZYX987... </b>| +-----------------------------+ +-----------------------------+
I need a connection between the php fetched data and the ajax fetched data.
I only know how to fetch all description at once but not how to fetch "img_title - ID:3" (php) with only "img_descr - ID:3" (ajax).
I thought about to fetch also the "img_id" and refering to that, ajax could fetch more data from database.
Here is my code (without img_id connection between php & ajax fetched data)
HTML & PHP:
<body>
<?php
$db = mysqli_connect("localhost", "root", "", "xy");
$result = mysqli_query($db, "SELECT * FROM images");
while ($row = mysqli_fetch_array($result))
{
echo "<button class='img_title'>Title: <b>" . $row['img_title'] . "</b></button><br>";
}
?>
<div id="descrs"></div>
</body>
JavaScrpit & AJAX
<script>
// Get the buttons (NodeList)
var buttons = document.querySelectorAll("button.img_title");
for(var x=0; x < buttons.length; x++) {
buttons[x].addEventListener('click', loadDescr);
}
function loadDescr(e)
{
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>
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);
?>