I’m currently trying to do the Quote Machine project, and I have the following code, that loads the first quote on the page:
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;
}
};
firstQuote();
Could somebody please explain me why firstQuote is not being executed? When I take the code outside the function it works perfectly.
I believe that jQuery.ajax assumes GET
and that some of your other set up is a bit off. I can get the following to work, with adjustments to your URL:
function firstQuote(){
jQuery.ajax({
url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=",
success: mycallback
});
function mycallback(json) {
console.log(json[0].content)
document.getElementById('quote').innerHTML = json[0].content;
}
};
firstQuote();
I might also point out that in code, it’s common to use $ as an abbreviation of jQuery and the callback can but put explicitly in the success - this might be a more common way to write it:
function firstQuote(){
$.ajax({
url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=",
success: function (json) {
console.log(json[0].content)
document.getElementById('quote').innerHTML = json[0].content;
}
});
};
firstQuote();
This isn’t required, but might be a more common way to do it.
1 Like
I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.