1

I'm trying to make a random quote machine, so I started out with this HTML to define the elements:

<div id="quoteDisplay">
  <h1 id="quote">Quote</h1>
  <h2 id="author">- Author</h2>
  <button id="new">New Quote</button>
</div>
$('#new').on('click', function(e) {
  e.preventDefault();
  $.ajax({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
      var post = data.shift();
      $('#author').html(post.title);
      $('#quote').html(post.content);
    }
  })
});

However for some reason when I click on the button, nothing happens and I don't understand where the problem is. I'm fully open to other methods of doing this.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

2 Answers2

1

The reason that the request isn't returning on jsFiddles, is due to the fact that the url entered results in a 'Mixed Content' error. (I.e., requesting a 'HTTP' source on a 'HTTPS' page.)

I think the reason that your code isn't working, is due to the fact that you haven't assigned the 'Document Ready' syntax to your jQuery file (If that is the full code for your JS file). As your code works as can be seen here.

This can be achieved through the shorthand syntax of

$(function() {
//YOUR CODE HERE
}

Or

$(document).ready(function(){
});
Joel
  • 100
  • 6
0

You're using $.ajax and one of the options of this method, is the method, which isn't specified.

To understand more about request methods, look at the jQuery docs: http://api.jquery.com/jquery.ajax/

The following code will work.

$.get({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
        /* process response */
    }
})

There is a working example here: http://jsfiddle.net/1chjtL6h/2/

Andrew Burns
  • 324
  • 4
  • 10