0
<script defer>
    var results = "";
$.getJSON('local node api ip',function(data){
  results = JSON.parse(data);

});
console.log(results);
var elem = document.createElement('div')
document.body.appendChild(elem)
elem.innerHTML = results.word
console.log('hello')
</script>

I want to parse the result of a local api but the function doesnt seem to run, and i have placed a console.log and that wasnt run. help!!!!

1 Answers1

0

// $.getJSON is async. You have to write code in callback. or use async-await

$.getJSON("local node api ip", function(results) {
  //const results = JSON.parse(data)
  console.log(results);
  var elem = document.createElement("div");
  document.body.appendChild(elem);
  elem.innerHTML = results.word;
  console.log("hello");
});

// Async Await

(async function() {
  let results = await $.getJSON("local node api ip");
  //results = JSON.parse(data);
  var elem = document.createElement("div");
  document.body.appendChild(elem);
  elem.innerHTML = results.word;
})();

// SAMPLE

$.getJSON("https://api.whatdoestrumpthink.com/api/v1/quotes/", function(results) {
 var elem = document.createElement("div");
  document.body.appendChild(elem);
  elem.innerHTML = results.messages.personalized;
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
xdeepakv
  • 7,835
  • 2
  • 22
  • 32