Hello everyone,
back in the days of kirby 2, @texnixe posted some nice instructions for an ajax call that requests one random $thing out of an array of $things …
I tried to adapt this to kirby 3’s new routing scheme, but again it seems I failed miserably in applying this.
Seems I’m getting a 404
status code, because api/random
does not exist. I’d like to use this code on my home
page to display one random image (plus, later, information like title and author) …
site/config/config.php
<?php
return [
'routes' => [
[
'pattern' => 'api/random',
'action' => function () {
$student = page('students')->children()->shuffle()->first();
$project = $student->children()->shuffle()->first();
$image = $project->images()->shuffle()->first();
return '<div class="gallery">';
return '<img src="' . $image->url() . '" alt="' . $image->uid() . '">';
return '</div>';
}
]
]
];
assets/js/reloadContainer.js
var container = document.getElementById("two");
var xhr = new XMLHttpRequest();
function reloadContainer() {
xhr.open("GET", "api/random");
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
container.innerHTML = xhr.responseText;
}
}
};
}
window.setInterval(reloadContainer, 5000);