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?
connexo
57.3k15 gold badges112 silver badges150 bronze badges
asked Jan 20, 2018 at 18:51
Caio Gomes
7891 gold badge12 silver badges24 bronze badges
-
@RishikeshDhokare Wrong.connexo– connexo2018年01月20日 18:54:18 +00:00Commented Jan 20, 2018 at 18:54
-
Yes, this is not the answerCaio Gomes– Caio Gomes2018年01月20日 18:54:48 +00:00Commented 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?S Raghav– S Raghav2018年01月20日 18:56:29 +00:00Commented 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 :)S Raghav– S Raghav2018年01月20日 18:58:43 +00:00Commented Jan 20, 2018 at 18:58
1 Answer 1
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>
answered Jan 20, 2018 at 18:56
Daniel Beck
21.7k5 gold badges43 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Caio Gomes
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.
Caio Gomes
And what is the normal way? I'm new to ajax and json.
Daniel Beck
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.)lang-js