0

I have this index.html file that contains a datatable that should be populated with data from a json file in the same folder. This is the index.html file:

<!DOCTYPE html>
<html>
<head>
<title>Display JSON File Data in Datatables | Example</title>
</head>
<body>
<table id="empTable" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script> 

<script type="text/javascript">
$(document).ready(function() {
    $('#empTable').dataTable({
        "ajax": "empdata.json",
        "columns": [
            {"data": "name"},
            {"data": "designation"},
            {"data": "office"},
            {"data": "extension"},
            {"data": "joining_date"},
            {"data": "salary"}
        ]
    });   
});
</script>
</body>
</html>

The problem is that the json file can't be loaded and I don't know how to fix it. This is the error in the console:

jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/user/Desktop/d/empdata.json?_=1504083178306. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.`

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
annie
  • 177
  • 2
  • 3
  • 15

2 Answers2

2

Given the path of the request, you're attempting to make the request to your local C:/ drive - browser security stops this from being allowed, for very good reasons.

To make the code work you need to run the request on a web server. You can easily install IIS or XAMPP to do this on your local machine.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

CORS Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.[1] A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.[2] Certain "cross-domain" requests, notably Ajax requests, however, are forbidden by default by the same-origin security policy.

Add a valid url to the request, same as where the server is running.

Fabio Marzocca
  • 1,573
  • 16
  • 36