6

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

Ionut
  • 724
  • 2
  • 9
  • 25

5 Answers5

9

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

Alex Repeckiy
  • 173
  • 10
  • you can't retrieve json from local file – Alex Repeckiy Dec 09 '15 at 13:32
  • Ok, but why on my base OS it worked? It displayed the json object on the webpage. – Ionut Dec 09 '15 at 13:34
  • sorry but i know, that you cant call by ajax local files, without server – Alex Repeckiy Dec 09 '15 at 13:45
  • create simple nodejs server, or set up apach, and work with it – Alex Repeckiy Dec 09 '15 at 13:46
  • 1
    Ok, but my questions is still available. Why on my base OS it worked without using any web server? – Ionut Dec 09 '15 at 13:55
  • What do you meen "base OS"? If you write path to your file in browser, he find your file local(using file system) and show you. Ajax - ( XmlHttpRequest), used http protocol for request, this req Handles by server. – Alex Repeckiy Dec 09 '15 at 15:24
  • Base OS is the OS which appears after the PC boots up when I turn it on. But I managed to run my code on VM WITHOUT any web server. The problem was the browser. I was testing it with Chrome. When I used Mozilla it worked fine. The problem I face now, after I implemented this program in VS 2013 professional and run it, it throws me at: alert('There was a problem with the server. Try again soon!'); Why? – Ionut Dec 10 '15 at 07:34
4

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");
    }
});
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
PrajaktaS
  • 49
  • 1
1

You may check if your JSON source requires internet connection, if YES then your VM must have internet connection working.

> Edit: Work around to read local JSON external file.
> 1. Create data.json file
> 2. Copy data into this file, for example:
>     data = '[{"Id" : "1", "name" : "abc"},{"id" : "2", "name" : "xyz"}]';
> 3. Include path for this file as reference:    <script type="text/javascript" src="data.json"></script>
> 4. Read JSON data by:    var jsonData = JSON.parse(data);
Ovais Khatri
  • 3,201
  • 16
  • 14
  • However my VM has internet connection. – Ionut Dec 09 '15 at 13:36
  • Try to access via VM browser address bar directly and check if it returns data or not! – Ovais Khatri Dec 09 '15 at 13:39
  • Sorry, but I didn't understand what you want me to do. – Ionut Dec 09 '15 at 13:46
  • I mean that URL you are using "data19.json", provide complete URL in browser address bar and hit enter, if it is displaying JSON data, put that URL in AJAX url parameter, there seems to be URL issue, it can't find URL and thus it throw 404 error. – Ovais Khatri Dec 09 '15 at 13:49
1

The json data you provided (inside data variable) is not an array, but a single object with property name and values. So don't loop through them. Instead loop through the properties of those and access the value using the property.

 items=[]; 
  for(r in data)
  {
      var key =r;
      var val=data[r];

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

  console.log(items);

Working sample here

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Many thanks. My problem is not the code, but why it is not working on my VM. It works only on my base OS. – Ionut Dec 09 '15 at 13:45
0

I think this will solution the problem. I tried it by myself.u can use it.


<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>How to retrieve data from JSON file using Jquery and ajax?</title>
    </head>
    <body>
    <div id="info"></div>
    </body>


----------


    <script type="text/javascript">
                    // script for Load 6 items at a time
                    var j=0; // index for start load in the object
                    var xdata; //A global variable for accessing it from inside the functions. it will load the file and do not want to read the file every time 
                    //loading the JSON file to object by Ajax
                    var xreq = new XMLHttpRequest();
                    xreq.open('GET', 'file.json');
                    xreq.onload = function () {
                        //convert the file from text to object after opened it , on load the file
                        xdata = JSON.parse(xreq.responseText);
                        // call funcation to Build the page
                        addHtml(xdata, j);
                        // added 6 to the index for start loading from the next items
                        j = j + 6;
                    };
                    //send ajax
                    xreq.send();

                    // when the page is ready and already the scroll access to end page call the building function again
                    $(document).ready(function () {
                            $(window).scroll(function () {
                                // get the scroll Position
                                var scrollPosition = $(window).scrollTop();
                                // Multiplication operation in 1.2 in order to call the function before arrival the end of the page with 20%
                                if (scrollPosition >= $(document).height() - ($(window).height())*1.2 && j < xdata.length) {
                                    addHtml(xdata, j);
                                    j = j + 6;
                                    xreq.send();
                                }
                            });
                        });

                    //funcation to Build the page
                    function addHtml(data,i) {
                        var info = document.getElementById("info");
                        var HtmlText ="";
                        // insert the HTML items before end a page
                        info.insertAdjacentHTML('beforeend',HtmlText);
                    }
                    </script>


----------


    </html>

<!-- end snippet Alwahashi 2017 -->
Hacker
  • 7,798
  • 19
  • 84
  • 154
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). You can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question once you have enough [reputation](https://stackoverflow.com/help/whats-reputation). - [From Review](/review/low-quality-posts/17950115) – Neil Nov 15 '17 at 07:35
  • I am Yemeniand i can't speak English as prefect and this answer is correctly . I tried it :-) – محمد الوهاشي Nov 16 '17 at 13:24
  • 1
    just i am trying to help. – محمد الوهاشي Nov 16 '17 at 13:25