Caio Gomes
Caio Gomes

Reputation: 768

Javascript function does not execute when called

I have the following code:

function firstQuote(){
  jQuery.ajax({
    url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
    type: 'GET',
    dataType: "jsonp",
  }); 

  function mycallback(json){
    document.getElementById('quote').innerHTML = json[0].content;
  }
};
window.onload = firstQuote;

It is a simple function, but it is not being executed. If I take the code outside of the function it works perfectly. I'm stuck at it for some time now. Please, could someone help me?

Upvotes: 0

Views: 49

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21485

You're trying to define the callback inside the firstQuote function. (If you look at the error console, you'll see "[Error] ReferenceError: Can't find variable: mycallback".) Separate those functions to put mycallback on the global scope:

function mycallback(json) {
  document.getElementById('quote').innerHTML = json[0].content;
}

function firstQuote() {
  jQuery.ajax({
    url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
    type: 'GET',
    dataType: "jsonp",
  });
};
window.onload = firstQuote;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="quote"></div>

Upvotes: 2

Related Questions