suRGE
suRGE

Reputation: 35

Trouble loading data from JSON file into HTML table with js function

The title says it all, I'm struggling to get data from a json file to an HTML table using a js function with jquery, but the data from the json file isn't loading onto the table. I'm also using bootstrap. I got the error Access to XMLHttpRequest at 'file:///C:/Users/Nuno/Desktop/my%20shit/Faculdade/ITW/trabalho%20lab/info.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

JSON:

[
    {"Age": "18", "Email": "[email protected]", "Phone": "123456789", "Adress": "Lisbon", "Languages": "English, Portuguese, (Limited) Spanish"}
]

JS:

    $(document).ready(function(){
  $.getJSON("info.json", function(data){
    var mydata = '';
    $.each(data, function(key,value){
      mydata += '<tr>';
      mydata+= '<td>'+value.age+'</td>';
      mydata+= '<td>'+value.email+'</td>';
      mydata+= '<td>'+value.phone+'</td>';
      mydata+= '<td>'+value.adress+'</td>';
      mydata+= '<td>'+value.languages+'</td>';
      mydata += '</tr>';
    });
    $('#personalInfo').append(mydata);
  });
  });

HTML:

<div class="table-responsive">
          <table class="table table-bordered table-striped" id="personalInfo"> 
              <tr> 
                <th> 
                  Age
                </th> 
                <th> 
                  Email 
                </th> 
                <th> 
                  Phone 
                </th> 
                <th> 
                  Adress
                </th> 
                <th> 
                  Languages
                </th> 
              </tr> 
          </table> 
        </div>

Upvotes: 0

Views: 204

Answers (2)

Renato Sant&#39;Anna
Renato Sant&#39;Anna

Reputation: 458

I'm guessing you're using Chrome. There's a restriction in Chrome on accessing any files via xhr requests starting with file: //.

There's more info here http://www.google.com/support/forum/p/Chrome/thread?tid=171316324d16747b&hl=en

Suggestion:

If you are using Google Chrome, it is intentional that AJAX on file:/// paths never works.

crbug/40787

Upvotes: 2

suRGE
suRGE

Reputation: 35

Thanks to all the help, if you ever have this issue check your console. If you get the error "Access to XMLHttpRequest at 'file:///C:/Users/Nuno/Desktop/my%20shit/Faculdade/ITW/trabalho%20lab/info.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https." The problem isn't the code. I managed to get it working using the Live Server extension in VS Code.

Upvotes: 0

Related Questions