0

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?

4
  • @RishikeshDhokare Wrong. Commented Jan 20, 2018 at 18:54
  • Yes, this is not the answer Commented Jan 20, 2018 at 18:54
  • @CaioCésarSilvaGomes can you clarify the "it is not being executed" bit. Did you try keeping breakpoints using the developer console/console.log something within the function to verify? Commented Jan 20, 2018 at 18:56
  • @connexo I was assuming the OP wanted the callback to be within so as to use JS closures or something :) Commented Jan 20, 2018 at 18:58

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

I get your point Daniel. Is there a way of getting the jsonp object and inserting it on the div quote with the same function? In this case firstQuote.
And what is the normal way? I'm new to ajax and json.
Hm....now that I try it, that particular server refuses the request unless you include that _jsonp param. So I guess in this case that is the way to do it. (Sorry, I'm more used to non-JSONP ajax, where you'd normally use the returned Promise, chaining a .then() or .success() or etc after the call.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.