I'm trying to create a feature that allows an empty div code snippet to be placed on the page and then for that to be replaced with more complicated markup with Javascript. The problem is that when there are more than one of these empty divs on the page it only displays one and the one it uses seems to be random. I think there is an issue with the loop.
I'm using data attributes on the div to store the database id of the required row.
<div data-foo="25"></div>
There can be any number of these on a page so the javascript needs to search for any element with a 'data-foo' attribute and then loop through them. The information is retrieved from the database and the output generated with a php file. This is returned to the javascript and replaces the empty div with the same data-foo id.
Javascritp/jQuery
var profiles = document.querySelectorAll('[data-foo]');
// console.log(profiles);
if(profiles.length) {
for(var i = 0; i < profiles.length; i++) {
var profileId = profiles[i].dataset.foo;
// console.log('[data-foo="' + profileId +'"]');
$.ajax({
url: '/file/path/profile.php',
data: {
profile: profiles[i].dataset.foo
},
type: 'get',
success: function(response) {
$('[data-foo="' + profileId + '"]').replaceWith(response);
}
});
}
}
PHP
The php runs for each id found by the js, using the loop above but I'm guessing only one is being output because the loop finishes before displaying it on the page?
if(isset($_GET['profile'])) {
try {
$sth = $dbh -> prepare("SELECT * FROM profiles WHERE id = :profile");
$sth -> bindParam(':profile', $_GET['profile'], PDO::PARAM_INT);
$sth -> execute();
} catch(PDOException $e) {
pdo_caught($e);
}
$result = $sth -> fetch(PDO::FETCH_ASSOC);
}
if(!empty($result)) {
echo '<div class="profile">
<img src="/img/'.$result["picture"].'" alt="'.$result['name'].'">
<h3>'.$result["name"].'</h3>
<p>'.$result["quote"].'</p>
</div>';
}