JSON response 404

Hello,

I am trying to get the data from the current page to use it in my JS.
The site structure looks like this:

  • Home
  • Projects
    • Project 1
    • Project 2
    • Project 3
  • About

So basically I’ve create the file “project.json.php” where I am sending the title as a test:

<?php

$data = array(
  'title' => (string)$page->title()
);

echo json_encode($data);

?>

And getting the retrieving the data from the “project.js” file

fetch('./project.json    ', {
    method: 'GET',
    headers: {
      'X-Requested-With': 'fetch'
    }
})
.then(function(response) {
    console.log(response);
    return response.json();
})

But I am getting 404 error because it is accessing “…/projects/project.json” and doesn’t exist. I am only able to get the data if I change manually the name of the URL in the “project.js” fetch to the name of the post ('./project-example.json') but that makes it less useful since I want to get the json data in my project.js for every post.

How can I get the data for each project I am in through “project.js”?

You indeed have to pass the url slug of the page, so if your HTML URL is https://mystarterkit.test/photography/trees the json version will live at https://mystarterkit.test/photography/trees.json, otherwise it wouldn’t make sense, because each child would have the same URL.

One way to fetch the correct page is to store the page id in a data attribute, maybe this cookbook is helpful: Load more with Ajax | Kirby CMS

1 Like

Thank you, it was very helpful!

I changed the url in the fetch to ('window.location.href' + .json) and it is working for every page now.