-3

I am doing a AJAX call pulling JSON data from a specific site but for some reason I am receiving and error before the call.

Error message:

Uncaught TypeError: Cannot read property 'addEventListener' of null at script.js:2

Code:

var ajaxtest = document.getElementById("dmeo");

ajaxtest.addEventListener("click",function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET","https://learnwebcode.github.io/json-example/animals-1.json")//post if you want to send data
ourRequest.onload = function(){
   // console.log(ourRequest.responseText);//test logging to console.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
ourRequest.send();
});
Ricardo Serra
  • 354
  • 2
  • 11
Charles
  • 17
  • 1
  • 7

2 Answers2

0

SOLVED! OK what I ended up doing was just putting it into a onclick event and it works.

function Makecall(){
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET","https://learnwebcode.github.io/json-example/animals-1.json")//post if you want to send data
ourRequest.onload = function(){
   // console.log(ourRequest.responseText);//test logging to console.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
ourRequest.send();
};
Charles
  • 17
  • 1
  • 7
-1

typo? var ajaxtest = document.getElementById("dmeo"); should be "demo"?

YoungLearnsToCoding
  • 377
  • 1
  • 2
  • 10
  • Yea thanks, that was the an issue as well but I changed it by doing an onclick event and adding the onclick event to my button in html. This was one of those moments where I asked before paying attention and working it out. Sorry about that. – Charles Mar 21 '17 at 18:46