0

I'm placing some order and storing the order information in a JSON file (order_details.json). This is how data look like :

[{
    "uniqueID": "CHECKOUT_IE01",
    "orderID": "4001820182",
    "date": "06-02-2019 16:55:32.321",
    "cartTotal": "€19.98"
}, {
    "uniqueID": "CHECKOUT_DK01",
    "orderID": "6001825057",
    "date": "06-02-2019 16:56:15.976",
    "cartTotal": "318 DKK"
}]

Now i want to make a HTML report where i can fetch all these data and can display in html format.

No idea which technology i have to use. What i have tried so far is, created js code as below:

var fs = require(['fs']);
var data = fs.readFileSync("D:\\order-detail.json", "utf8");
var data1 = JSON.parse(data);
console.log(data1);
var unique_id = data1[0].uniqueID;  
var order_id = data1[0].orderID;    
var order_date = data1[0].date; 
var cart_total = data1[0].cartTotal;

document.getElementById("uid").innerHTML = unique_id;
document.getElementById("oid").innerHTML = order_id;
document.getElementById("date").innerHTML = order_date;
document.getElementById("ctotal").innerHTML = cart_total; 

and HTML

<body onload="myFunction()">
<h3>Values from Json</h3>
<div>
<span id="uid"></span>
<span id="oid"></span>
<span id="date"></span>
<span id="ctotal"></span>
</div>

But its not working, I'm getting below error in console-

dashboard.html:8 Uncaught TypeError: fs.readFileSync is not a function
    at myFunction (dashboard.html:8)
    at onload (dashboard.html:25)
myFunction @ dashboard.html:8
onload @ dashboard.html:25
require.js:5 GET file:///D:/JSON/fs.js net::ERR_FILE_NOT_FOUND
req.load @ require.js:5
load @ require.js:5
load @ require.js:5
fetch @ require.js:5
check @ require.js:5
enable @ require.js:5
enable @ require.js:5
(anonymous) @ require.js:5
(anonymous) @ require.js:5
each @ require.js:5
enable @ require.js:5
init @ require.js:5
(anonymous) @ require.js:5
setTimeout (async)
req.nextTick @ require.js:5
o @ require.js:5
requirejs @ require.js:5
myFunction @ dashboard.html:7
onload @ dashboard.html:25
require.js:5 Uncaught Error: Script error for "fs"
http://requirejs.org/docs/errors.html#scripterror
    at makeError (require.js:5)
    at HTMLScriptElement.onScriptError (require.js:5)

i'm not sure whats wrong or the way i'm using is wrong. Any help would be great appreciated

NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • Have you tried changing `var fs = require(['fs']);` to `var fs = require('fs');`? – nick zoum Feb 07 '19 at 07:41
  • Yes i did, that time i was getting `Uncaught Error: Module name "fs" has not been loaded yet for context: _. Use require([])` – NarendraR Feb 07 '19 at 07:43
  • 1
    Are you using `Node` or similar framework? because in plain browser JavaScript, `require` is not a function. And when using `Node` the proper syntax is `require('fs');` – nick zoum Feb 07 '19 at 07:45
  • 1
    You're mixing node.js with browser javascript. `require` is only available due to coincidence - it's being supplied by whatever module bundler you're using. Even if you could load `fs`, it wouldn't work. Look in to the fetch api to learn how to load data in the browser (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – Christian Scott Feb 07 '19 at 07:48

3 Answers3

1

I think you are mixing Node with plain Browser JavaScript. Normal JavaScript does not have a definition for require, if it does it is because another library you are using has declared it will not do what you are expecting. The simplest way to load data from a browser is using an XMLHttpRequest, here is an example:

loadURL("file:///D:/order-detail.json", onDataLoaded);

function onDataLoaded(data) {
  data = JSON.parse(data);
  var unique_id = data[0].uniqueID;
  var order_id = data[0].orderID;
  var order_date = data[0].date;
  var cart_total = data[0].cartTotal;

  document.getElementById("uid").innerHTML = unique_id;
  document.getElementById("oid").innerHTML = order_id;
  document.getElementById("date").innerHTML = order_date;
  document.getElementById("ctotal").innerHTML = cart_total;
}

function loadURL(url, callBack) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.onloadend = onLoadEnd(xhr, callBack);
  xhr.send();
}

function onLoadEnd(request, callBack) {
  return function() {
    var status = request.status;
    var result = String(request.response);
    if (status >= 200 && status < 300) callBack(result);
  };
}

Due to security reasons, some browsers (i.e. Chrome) might block the request. To resolve this, try adding the JSON file to your IIS (and then change file://D:\\order-detail.json to localhost/addPathHere/order-detail.json). Here is a simple tutorial to activate your local IIS server (assuming you are using windows).

nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • `Uncaught ReferenceError: method is not defined` and location is `xhr.open(method, url, true);` – NarendraR Feb 07 '19 at 08:37
  • @NarendraR Sorry, change `method` to `"GET"`. I've edited the answer – nick zoum Feb 07 '19 at 08:38
  • Now `jquery.min.js:2 Access to XMLHttpRequest at 'file:///D:/JSON/order-detail.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes:` – NarendraR Feb 07 '19 at 08:42
  • 1. `jquery.min.js:2`? How did that appear? I didn't use any jQuery in my answer. 2. That behavior is expected when using chrome (as stated in the answer). Try firefox or adding the json to your IIS – nick zoum Feb 07 '19 at 08:44
  • issue is with chrome i can see the result in firefox – NarendraR Feb 07 '19 at 08:47
  • Are there any further questions and/or problems regarding the issue? If not, can you please accept an answer? – nick zoum Feb 07 '19 at 09:02
1

This should work.

Replace ./JSON/order-detail.json with your json file path.

$.getJSON('./data.json', function(item) {
  item.forEach(function(data) {
    return [
      document.getElementById("uid").innerHTML += data.uniqueID + "</br>",
      document.getElementById("oid").innerHTML += data.orderID + "</br>",
      document.getElementById("date").innerHTML += data.date + "</br>",
      document.getElementById("ctotal").innerHTML += data.cartTotal + "</br>"
    ];
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Values from Json</h3>
<div>
  <span id="uid"></span>
  <span id="oid"></span>
  <span id="date"></span>
  <span id="ctotal"></span>
</div>
O.O
  • 1,389
  • 14
  • 29
  • Getting this `jquery.min.js:2 Access to XMLHttpRequest at 'file:///D:/JSON/order-detail.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes:` – NarendraR Feb 07 '19 at 08:30
  • @NarendraR try using a relative path i.e. `./JSON/order-detail.json`. let me know if that works. – O.O Feb 07 '19 at 08:37
  • issue is with chrome i can see the result in firefox – NarendraR Feb 07 '19 at 08:46
  • 1
    Yeah this is due to security, try using a localhost to run your project. See this answer for details `https://stackoverflow.com/a/10752078/7626277` hope that helps. – O.O Feb 07 '19 at 08:49
0

You are using NodeJS pattern in Client side javascript. In front-end You can import JSON file directly using jQuery.

$(function(){
        $.getJSON('order-detail.json',function(data){
            $.each(data,function(i,order){

             //your implementation here..
             // Can access data like order.uniqueID , order.orderID

            });
        }).error(function(){
            console.log('error');
        });
    });

The .json file should be accessible under your domain like CSS,JS,Image resources. You can't access with full path like C:\yourpath\file.json

BadPiggie
  • 5,471
  • 1
  • 14
  • 28