0

I am using Aptana Studio 3 text editor and working on Windows 7 Enterprise OS. I have the following AJAX code which is not working on the local system to fetch JSON files kept on an https website. This example is taken from the Youtube video:

JSON and AJAX Tutorial: With Real Examples

index.html:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta name="test" content="content"/>
        <title>JSON and AJAX</title></head>
<header>
  <h1>JSON and AJAX</h1>
  <link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
</header>


<body>
 <script src="main.js"></script>
 <button type="button" onclick="function()" id="btn">Fetch Info for 3 New Animals</button>
 <div id="animal-info"> </div>
</body>

</html>

Styles.css:

    html, body {
  padding: 0;
  margin: 0;
}

.hide-me {
  visibility: hidden;
  opacity: 0;
  transform: scale(.75);
}

h1 {
  margin-top: 0;
  font-size: 2.4em;
  font-weight: normal;
  display: inline-block;
}

body {
  font-family: Helvetica, sans-serif;
  padding: 50px 10%;
}

button {
  background-color: #046380;
  color: #FFF;
  border: none;
  padding: 10px 15px;
  font-size: 15px;
  border-radius: 4px;
  cursor: pointer;
  outline: none;
  box-shadow: 2px 2px 0 #034154;
  margin-bottom: 10px;
  margin-left: 18px;
  transition: opacity .4s ease-out, transform .4s ease-out, visibility .4s ease-out;
  position: relative;
  top: -10px;
}

button:hover {
  background-color: #034F66;
}

button:active {
  background-color: #034154;
  box-shadow: none;
  position: relative;
  top: -8px;
  left: 2px;
}

p {
  padding: 4px 0 2px 8px;
  line-height: 1.7;
  border-bottom: 1px dotted #DDD;
  list-style: none;
  margin: 0;
}

main.js:

    var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("onClick", function() {  
  var ourRequest = new XMLHttpRequest();
  ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
  //ourRequest.open('GET', 'animals-' + pageCounter + '.json');
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }

  };

  ourRequest.onerror = function() {
    console.log("Connection error");
  };

  ourRequest.send();
  pageCounter++;
  if (pageCounter > 3) {
    btn.classList.add("hide-me");
  }
}
);


function renderHTML(data) {
  var htmlString = "";

    for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";

    for (ii = 0; ii < data[i].foods.likes.length; ii++) {
      if (ii == 0) {
        htmlString += data[i].foods.likes[ii];
      } else {
        htmlString += " and " + data[i].foods.likes[ii];
      }
    }

    htmlString += ' and dislikes ';

    for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
      if (ii == 0) {
        htmlString += data[i].foods.dislikes[ii];
      } else {
        htmlString += " and " + data[i].foods.dislikes[ii];
      }
    }

    htmlString += '.</p>';

  }

  animalContainer.insertAdjacentHTML('beforeend', htmlString);
}

This code doesn't seem to work on my local machine. I tried running it by installing an http-server using NodeJs on my local machine, but still no joy!

Another JSON AJAX code on ww3Schools.com

though seems to work fine. This is an inline javascript code in the html file. Initially i thought onReadyStateChange was the culprit not working on IE, FF, CH etc., but this website code also has onReadyStateChange but it works fine!

Or is it the Button click event handler the cause why it is not working?

btn.addEventListener("onClick", function() {  

My code is not inline, could that be the reason? If not, what am i missing or doing wrong?

sifar
  • 1,086
  • 1
  • 17
  • 43

2 Answers2

1

I modified html file by moving "div" above "script" tag:

index.html:

    <!DOCTYPE html>
<html>
    <head>
        <meta name="test" content="content"/>
        <title>JSON and AJAX</title></head>
<header>
  <h1>JSON and AJAX</h1>
  <link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
 <button type="button" onclick="function()" id="btn">Fetch Elements</button>
 <div id="animal-info"> </div>
</header>

<body>
 <script src="main.js"></script>
</body>

</html>

main.js:

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

  btn.addEventListener("click", function() {  
  // function LoadJSON() {
      if (window.XMLHttpRequest) {
        // code for modern browsers
        var ourRequest = new XMLHttpRequest();
        } else {
        //code for IE6, IE5
        var ourRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }

      // ourRequest.onLoad = function() {    
      ourRequest.onreadystatechange = function() {
          if (this.readyState = 4 && (this.status >= 200 && this.status < 400)) {
            var ourData = JSON.parse(ourRequest.responseText);
            renderHTML(ourData);
            } else {
            console.log("We connected to the server, but it returned an error.");
          }
      };

      ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
      // ourRequest.open('GET', 'animals-' + pageCounter + '.json');
      ourRequest.send();

      ourRequest.onerror = function() {
      console.log("Connection error");
      };

      pageCounter++;
      if (pageCounter > 3) {
        btn.classList.add("hide-me");
      }
  }
);

function renderHTML(data) {
  var htmlString = "";
    for (i = 0; i < data.length; i++) {
        htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";

            for (ii = 0; ii < data[i].foods.likes.length; ii++) {
              if (ii == 0) {
                htmlString += data[i].foods.likes[ii];
              } else {
                htmlString += " and " + data[i].foods.likes[ii];
              }
            }
            htmlString += ' and dislikes ';

            for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
              if (ii == 0) {
                htmlString += data[i].foods.dislikes[ii];
              } else {
                htmlString += " and " + data[i].foods.dislikes[ii];
              }
            }   
            htmlString += '.</p>';
        }
        // animalContainer.insertAdjacentHTML('beforeend', htmlString);
        animalContainer.innerHTML=htmlString;
}

This works now!

The only problem i am facing is if i have more json files on the server, how do i hide ("hide-me") the button based on the number of json files processed, when button is clicked a no of times?

Right now, it hides button if pageCounter exceeds 3.

      if (pageCounter > 3) {
    btn.classList.add("hide-me");
  }

The other issue i see is if i enable "insertAdjacentHTML", it displays each json twice. Why is this happening?

// animalContainer.insertAdjacentHTML('beforeend', htmlString);
sifar
  • 1,086
  • 1
  • 17
  • 43
  • I had a similar issue with a really old code, and I have solved it thanks to part of this answer, by defining the _onreadystatechange_ function **before** the _open_ function. – Benjamín Valero Mar 14 '22 at 12:56
0

Use this:

btn.style.visibility = "hidden";

Erick Mg
  • 41
  • 1
  • 3