skip to Main Content

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


  1. 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 your fetch/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:

    const jsonData = require("/path/to/club_mems.json");
    
    or
    
    import jsonData from "/path/to/club_mems.json"
    

    access JSON file

    Login or Signup to reply.
  2. try this solution:

    function cccrFlow() {
        club_mems = fetch('assets/club_mems.json')
        .then(response => response.json())
        .then(data => {
            console.log(data)
            alert(data);
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search