Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data from JSON file using Jquery and ajax?

Tags:

json

jquery

ajax

A weird thing happened to me today: I was trying to retrieve some data from a JSON file using jquery and ajax, and display this data on a webpage. This example, which I found on the Internet, worked for me on the base OS. When I try run it from a virtual machine with Win10 OS it doesn't work, meaning that it throws me to: alert('There was a problem with the server. Try again soon!');. Why? Many thanks in advance!

This is in my data19.json file:

 {
  "one": "Learned Optimism",
  "two": "Deliberate Practice",
  "three": "Getting Things Done"
}

My script, script19.js, is:

$(function() {  
  $('#clickme').click(function() {
       $.ajax({
       url: 'data19.json',
       dataType: 'json',
       success: function(data) {
          var items = [];

          $.each(data, function(key, val) {

            items.push('<li id="' + key + '">' + val + '</li>');    

          });

          $('<ul/>', {
             'class': 'interest-list',
             html: items.join('')
          }).appendTo('body');

       },
      statusCode: {
         404: function() {
           alert('There was a problem with the server.  Try again soon!');
         }
       }
    });
  });
});

My HTML file is:

 <!DOCTYPE html>
<html>
<head>
  <title>19. Using jQuery to retrieve JSON via AJAX</title>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="script19.js"></script>
</head>
<body>
  <h1 id="title">19. Using jQuery to retrieve JSON via AJAX</h1>

  <a href="#" id="clickme">Get JSON Data</a>
</body>
</html>

Also when I click "Get JSON Data" this is what appears in Console: enter image description here

like image 619
Ionut Avatar asked Dec 09 '15 13:12

Ionut


2 Answers

your code is corect, you must move your code to server, on server your ajax call json, all will be work.

like image 71
Alex Repeckiy Avatar answered Oct 13 '22 05:10

Alex Repeckiy


Please try using mozilla browser for this scenario. I have also faced the same issue in chrome but it works fine on mozilla. try adding "type" parameter with value "Get" for ajax request. Refer this one -

$.ajax({
    type: "Get",
    url: "data.json",
    dataType: "json",
    success: function(data) {

    },
    error: function(){
        alert("json not found");
    }
});
like image 37
PrajaktaS Avatar answered Oct 13 '22 04:10

PrajaktaS