This code below works in PHP but not in JS. Can you tell me why? How can I make the pure JS version work?
async function cccrFlow() {
response = await fetch('assets/club_mems.json');
club_mems = [];
club_mems = await response.json(); // DOESN"T WORK
}
function cccrFlow() {
club_mems = <?php include('assets/club_mems.json');?>; // WORKS PERFECTLY
}
club_mems.json
[{"Name":"Ahmedistan, Jamshed","clubEXP":"2022-09-15"},{"Name":"Anaizi, Paul N","clubEXP":"2021-01-27"},{"Name":"Anderson, Simon","clubEXP":"2022-06-30"},{"Name":"Ashes, Bob P","clubEXP":"2022-04-21"}]
2
Answers
When you use fetch, you have to make sure that whatever asset/resource you are loading – is publicly accessible. In short,
if you use this URL in browser
http://yourserver.com/assets/club_mems.json
and you can see the response in the browser, then yourfetch/async/await
will work (see screenshot).If you don’t want to expose your data in public domain, then you will have to include the JSON file using one of the module loading methods i.e.
import/require
.EDIT
To achieve this: you need to have some kind of module loader in your development environment. The module loader will make sure that once you build your application for prod environment, your code includes the JSON data without any issue.
There are different options: webpack, bundlr, parcel etc. Checkout their official websites for how to set them.
Once you set this up, you can simply write in your code:
try this solution: