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

6

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

Hourigan answered 9/12, 2015 at 13:26 Comment(1)
you can't retrieve json from local file, so you should set up a server, something like: localhost:8080/C9HS_19.htmlMeasurement
T
9

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

Tank answered 9/12, 2015 at 13:31 Comment(7)
you can't retrieve json from local fileTank
Ok, but why on my base OS it worked? It displayed the json object on the webpage.Hourigan
sorry but i know, that you cant call by ajax local files, without serverTank
create simple nodejs server, or set up apach, and work with itTank
Ok, but my questions is still available. Why on my base OS it worked without using any web server?Hourigan
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.Tank
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?Hourigan
S
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");
    }
});
Salot answered 23/5, 2018 at 15:51 Comment(1)
one of the perks of jQuery is cross browser support, if it works on one and not the other something is wrong with the codeStowers
C
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);
Calabro answered 9/12, 2015 at 13:34 Comment(4)
However my VM has internet connection.Hourigan
Try to access via VM browser address bar directly and check if it returns data or not!Calabro
Sorry, but I didn't understand what you want me to do.Hourigan
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.Calabro
S
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

Spacial answered 9/12, 2015 at 13:35 Comment(1)
Many thanks. My problem is not the code, but why it is not working on my VM. It works only on my base OS.Hourigan
R
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 -->
Regeneration answered 15/11, 2017 at 6:50 Comment(3)
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 ReviewTycoon
I am Yemeniand i can't speak English as prefect and this answer is correctly . I tried it :-)Tieratierce
just i am trying to help.Tieratierce
A
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.

Archer answered 9/4 at 21:29 Comment(1)
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.Dietz

© 2022 - 2024 — McMap. All rights reserved.