Getting JSON to work - Build a Random Quote Machine

Getting JSON to work - Build a Random Quote Machine
0

#1

Can someone explain why my code isn’t working? My ultimate goal with this code is to get a JSON object from quotesondesign.com. I’m making use of JSONP but it doesn’t work. Can someone review my code and educate? I’d also take any resources on learning to use ajax.

The success and always case just have html functions so I can see if they run.

Code:

$('h2').on('click', function(e) {
    
    $.ajax({
    url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
 
    jsonp: "callback",
 
    dataType: "jsonp",
 
    success: function( response ) {
      console.log( response ); // server response
      $("#quoteContent").html("Byee");
    },
      
    always: function(response) {
      $("#quoteContent").html("Yoo");
    } 
    
});
});

#2

I’ve edited your post for readability. When you enter a code block into the forum, 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.

What does your solution not do that you expect it should do? Do you have any errors showing in the browser’s console (Ctrl+Shft+J in Chrome)? If you do have errors there, you need to resolve them first.

Also, why are you using jsonp for the dataType?


#3

Try getting rid of your jsonp option, and get rid of the _jsonp=mycallback in your URL.


#4

That won’t work. That causes cross origin problems apparently.


#5

It seems that despite what the documentation says on quotesondesign.com, we’re not actually going to be using JSONP. Do as suggested before, but also add a CORS proxy to make the request work. https://cors-anywhere.herokuapp.com is an easy choice. Prepend it to the URL like so: https://cors-anywhere.herokuapp.com/http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1


#6

Wow. This looks promising. Thanks for the help.


#7

I am not sure CORS is necessary. I used the following to get data for my Random Quote Machine with no issues.

     $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",
      function(data) {
        console.log(data);
    }); 

The only extra code I had to add the following before the $.getJSON call to get the
quotesondesign.com APT to not cache the response and get a different quote each time.

 $.ajaxSetup({cache:false});

#8

Ah, I didn’t realize that quotesondesign now uses HTTPS. Good call, that’s better than using a proxy for sure.


#9

Huh. It words now. It seems that changing to http to https fixed it. Thanks all!