Hello fellow campers,
I’ve been reading documentation over and over, but can’t seem to figure out why the JSON data isn’t loading onto my page. Here’s the API I’m using:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
and here’s my code:
$.ajax({
url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",
cache: false,
dataType: "json",
success: function(json) {
$("#text").html(json[0].content);
$("#author").html(json[0].title);
}
});
and codepen:
Any feedback would be appreciated. Thanks.
noyb
September 2, 2017, 3:10am
2
Hey. You need to add an “s” in the http, otherwise the request won’t be allowed. I would also suggest to “dry” up your code a bit, having the same ajax call two times seems like it could be optimized.
Thank you so much. It works fine now. Yeah, I’m going to throw it into its own function now that I’m done staring at it for hours. Thanks again!
1 Like
noyb
September 2, 2017, 3:28am
4
No problem! Since you are using jQuery, you could easily call the function that will wrap your ajax call via the .trigger() method.
Something like this:
function getQuote() {
// Ajax call
}
$("#randomize").click(function() {
// Stuff
getQuote();
}).trigger('click');
This way the click will be triggered once (displaying a quote when the first time the page will load), and then it will call your function as usual.
Very cool. Works perfect!