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

1
  • you can't retrieve json from local file, so you should set up a server, something like: localhost:8080/C9HS_19.html Commented Dec 9, 2015 at 13:29

6 Answers 6

9

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

Sign up to request clarification or add additional context in comments.

7 Comments

you can't retrieve json from local file
Ok, but why on my base OS it worked? It displayed the json object on the webpage.
sorry but i know, that you cant call by ajax local files, without server
create simple nodejs server, or set up apach, and work with it
Ok, but my questions is still available. Why on my base OS it worked without using any web server?
|
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");
    }
});

1 Comment

one of the perks of jQuery is cross browser support, if it works on one and not the other something is wrong with the code
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

1 Comment

Many thanks. My problem is not the code, but why it is not working on my VM. It works only on my base OS.
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);

4 Comments

However my VM has internet connection.
Try to access via VM browser address bar directly and check if it returns data or not!
Sorry, but I didn't understand what you want me to do.
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.
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 -->

3 Comments

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review
I am Yemeniand i can't speak English as prefect and this answer is correctly . I tried it :-)
just i am trying to help.
0

You are supposed to be giving Jquery a URL in the url property.

just a file name is interpreted as a relative HTTP url and the OS may or may not return this for you.

Try coding it as a FILE url, you can find this by opening the json file directly in a browser and copying the URL from the address line.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.