Fetch specific translation of content with AJAX request?


#1

Hi.

I’m making a simple AJAX request to fetch some text content which is then placed on a page. It works perfectly fine, but when I switch to the German version of the site, the AJAX request still fetches the English text. How do I specify that the request should get the translated version of the content?

My AJAX request looks like this (simplified):

$(document).ready(function() {
  var teamMemberButton = $(".slider--cell.portrait");
  var container_teamMemberText = $("#teamMemberText");
  var url = "team" + ".json";
  //
  teamMemberButton.click(function() {
    var teamMember_clicked = $(this).data("member");
    //
    console.log("Team member clicked: " + teamMember_clicked);
    //
    $.ajax({
      type: "POST",
      url: url,
      data: { teamMemberURL: teamMember_clicked },
      success: function(data) {
        container_teamMemberText.text(data.text);
      }
    });
  });
});

It simply checks the »Team Member« that was clicked and gets the related text. The corresponding JSON template looks like this:

// Target Member

$target = $_POST['teamMemberURL'];

$teamMember_text = '';

// Access CMS

$page = page('team');

$teamMember = $page->children()->find($target);

// Get text of team member

$teamMember_text .= $teamMember->item1();

$data['text'] = $teamMember_text;

echo json_encode($data);

I suspect that somewhere I have to specify which translation of the text I want fetched, but I don’t know where or how. Thanks to anyone who can help me out :slight_smile:


#2

You can get the content of a specific language like this:

$text = $page->content('de')->item();

So you would have to pass the current language to your script (maybe via a data attribute), then add it to your data attribute in the Ajax request, so that you can read it again in the JSON template.


#3

Thanks! I knew that there had to be simple way like this. Gotta love Kirby.

Is there a way for me to simply check the current language the site is viewed in or do I have to add a specific data-attribute to all elements that trigger the AJAX request?

I could attach the current language to the element triggering the request like so:

<button data-language="<?= $site->language()->name() ?>"> My Button </button


#4

Well, you could get the language from the URL or from the html element’s lang attribute (if that is set correctly), but then you might as well just send with a data attribute. Your JavaScript is not aware what language the server has delivered, it can only “see” what is in the browser.