Issue
I am trying to add some data to a Website and i want to fetch the data from a json file. and i want to use the data from this file in whole website.
can you suggest a method that will help me to fetch it once so that i don't have to fetch multiple times. because the original file may contain more than 50,000 data.
And my json is in this format and it is stored on the server in a file named
data.json
[
{
"Department": "ABC-1",
"Date": "03-Jan-22",
"Name": "Jane Doe",
"Project": 1,
"Section": 1,
"Task_Code": 999,
"Time": 32,
"Activity_Code": "1_1"
},
{
"Department": "ABC-2",
"Date": "03-Jan-22",
"Name": "Joe Doe",
"Project": 1,
"Section": 1,
"Task_Code": 93,
"Time": 8,
"Activity_Code": "1_1"
},
{
"Department": "ABC-2",
"Date": "03-Jan-22",
"Name": "Jane Doe",
"Project": 1,
"Section": 1,
"Task_Code": 99,
"Time": 8,
"Activity_Code": "1_1"
},
{
"Department": "ABC-1",
"Date": "03-Jan-22",
"Name": "Joe Doe",
"Project": 1,
"Section": 1,
"Task_Code": 98,
"Time": 8,
"Activity_Code": "1_1"
},
{
"Department": "ABC-2",
"Date": "03-Jan-22",
"Name": "Joe Doe",
"Project": 1,
"Section": 1,
"Task_Code": 99,
"Time": 32,
"Activity_Code": "1_1"
},
{
"Department": "ABC-1",
"Date": "03-Jan-22",
"Name": "Jane Doe",
"Project": 1,
"Section": 1,
"Task_Code": 93,
"Time": 8,
"Activity_Code": "1_1"
}
]
and I have written a test hscript.js file to parse the json. and i am able to fetch the file inside the script file but when i try to call the variable inside the webpage it does not recognize variable.
index.html
`<!DOCTYPE html>
<html lang="en">
<head>
<!--script src="js/hscript.js"></script-->
</head>
<body>
File Active
<!--script type="module" src="js\index.js"></script-->
<script type="module" src="js/hscript.js"> </script>
<script >
console.log(dataset.length); /variable not returning any value
</script>
</body>`
hscript.js
fetch('../js/data.json')
.then(response => response.json())
.then(data => console.log(data.length)) //here i get the Console data
When i run the above code i get the console output as per the comment in the code.
Please help i have very less knowledge on jquery.
Solution
The problem is that your console.log is executed before your AJAX call is finished. You should make the following changes:
#1 Add a function called onDataReady before your hscript.js call:
<script>
function onDataReady(data) {
console.log(data.length)
}
</script>
#2 Update your hscript.js code to call the onDataReady once data is fetched:
fetch('../js/data.json')
.then(response => response.json())
.then(data => onDataReady(data))
Answered By - Hazem Hagrass
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.