I have a very basic AJAX structure set up in order to asynchronously fetch data (a paragraph of text) from subpages when a button is clicked.
The structure starts with the markup of the buttons:
<div id="button_teamMember1" data-member="team-member-1" onclick="load_teamMember()">
<span>Team Member One</span>
</div>
<div id="button_teamMember2" data-member="team-member-2" onclick="load_teamMember()">
<span>Team Member Two</span>
</div>
<div id="button_teamMember4" data-member="team-member-3" onclick="load_teamMember()">
<span>Team Member Three</span>
</div>
When either one of the buttons is clicked, the following script is executed:
function load_teamMember() {
//
var memberText = $("#memberText");
var url = "team.json";
//
$.get(url, function(data) {
memberText.text(data.html);
});
}
This script accesses the JSON template of my »Team« page. Note that the team page is invisible, it sits in the backend containing the team members as subpages; the content of these subpages is (supposed to be) displayed on a different page, which also contains the buttons mentioned above.
What I would like to achieve is the following: When either of the buttons is clicked, the AJAX script accesses the JSON template and (somehow) fetches the text from the correct/relevant team-member-subpage (i.e. the second button is clicked = the text of Team Member Two is fetched). That’s why I added the data-member attribute; it contains the internal URL of the member’s subpage.
I know how to fetch data statically from a specific subpage via AJAX. That’s what I am currently doing in the JSON template which the script is accessing. It works and looks like this:
<?php
$html = '';
$page = page('j2c-team');
$member = $page->children()->find('team-member-1');
//
$html .= $member->biography();
//
$data['html'] = $html;
echo json_encode($data);
How can I do this dynamically so a click on the button fetches the text of the relevant member?
Is there a way for me to somehow pass the value of data-member
of the button clicked on to the JSON template in order to fetch the correspondent subpage of my »Team« page?
I’d greatly appreciate any help with this.
(Note: I’m super new to working with AJAX.)