day 120 — code 365

Sun 10 Apr 2016

I managed to get through the tutorial To Do app.

It works.

I don’t really understand all of the code — I made a lot of code comments, and drew out on paper the structure, and some relationships within the code… but I still feel like there is a LOT of understand.


I decided to take a break and work on my portfolio page.

I found this great API at http://quotesondesign.com/, and I tried to implement it into a test page. As it turned out, it ended up being a lot of time spent practising my AJAX skills….

My initial AJAX call:

$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1'
});

Got this error:

XMLHttpRequest cannot load http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1. The 'Access-Control-Allow-Origin' header has a value 'http://null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

Which made realise that I needed to use JSONP.

So I tried this:

$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
dataType: 'jsonp'
});

Which got me this error:

Refused to execute script from 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_p…age]=1&callback=jQuery1123012326284124289244_1460269452955&_=1460269452956' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Having made it eventually work, I now realise that error meant that the server had sent back a JSON object but I was trying to process it as JSONP, which is a function, and which needs to be executed.


So I tried this:

$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?mycallback',
jsonpCallback: 'mycallback',
dataType: 'jsonp'
});

This worked! But I read in the jQuery documentation that its best to let jQuery set the callback function name.


And I finally managed to make it work like so:

$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType: 'jsonp'
});

Hurray!

It took too long to achieve this to do anything on my portfolio, but I feel like I have a (better) grasp of JSON / JSONP…


Thanks for stopping by!

Like what you read? Give Ampers Smith a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.