0

I have solved the issue, thanks to everyone who commented and helped. The solution is in the comments.

I am new in Javascript, AJAX, Json.

I have a 3 files:

index.html

 <script src="example.js"></script>
<a href="#" id="get-data">Get JSON data</a>
    <div id="show-data"></div>

example.js

$(document).ready(function () {
  $('#get-data').click(function () {
    var showData = $('#show-data');

    $.getJSON('example.php', function (data) {
      console.log(data);

      var items = data.items.map(function (item) {
        return item.key + ': ' + item.value;
      });

      showData.empty();

      if (items.length) {
        var content = '<li>' + items.join('</li><li>') + '</li>';
        var list = $('<ul />').html(content);
        showData.append(list);
      }
    });

    showData.text('Loading the JSON file.');
  });
});

and example.php

{
  "items": [
    {
      "key": "First",
      "value": 100
    },{
      "key": "Second",
      "value": false
    },{
      "key": "Last",
      "value": "Mixed"
    }
  ],
  "obj": {
    "number": 1.2345e-6,
    "enabled": true
  },
  "message": "Strings have to be in double-quotes."
}

On the server/hosting it is running and fetching the data. On the localhost, on my computer it does not fetches the data, it only says "Loading the JSON file.".

On localhost the index.html gets example.js from the server and example.php is also on the server in same directory with example.js.

Please help me to understand why it does not working, also probably the localhost should have installed node.js?

John Doe
  • 67
  • 1
  • 2
  • 8
  • 2
    Any errors in your JavaScript console? – Brett Gregson May 14 '16 at 11:34
  • 1
    What is the result of your `console.log(data);`? Something, nothing, `undefined`..? Also check the network tab in your console - is it getting the data ok? – Andy May 14 '16 at 11:34
  • 1
    I have forgot to check the console, thanks a lot - it really helped me as it stated that there is no access to the file. I have putted: "header('Access-Control-Allow-Origin: *'); " and it worked perfectly. Thanks again! – John Doe May 14 '16 at 11:37
  • Maybe the server tries ti execute the php and localhost not? – dec May 14 '16 at 11:37
  • I've mocked [your code and it works](https://jsfiddle.net/yz9f7gog/1/https://jsfiddle.net/yz9f7gog/1/) so something else is going on. Ah, just saw your comment. – Andy May 14 '16 at 11:42
  • 1
    @andy thanks anyways :) – John Doe May 14 '16 at 11:52

0 Answers0