Ajax without jQueryAugust 18, 2014 - Tim Evko
Since coming to understand this, I’ve put myself on a strict no-jQuery diet, in order to better understand the language. So far, I have learned a lot, one of the many lessons being just how much work jQuery does for you behind the scenes.
So there I was, on my no-jQuery diet, when I came across a problem. I needed to use AJAX. Specifically, I needed to get data from Dribbble’s REST API and display it on my website. This was a problem because I couldn’t just
$.getJSON my way to safety. This time I had to do it the hard way. So I gritted my teeth, swallowed my pride, and did what any web developer does when they reach a problem: lot’s of googling.
The first thing that caught my eye was a grouping of keywords, CORS, JSON, and JSONP. I knew what JSON was, but I was unsure of the other two. As it turns out, they’re both pretty important, and worth a quick review.
JSONP, or JSON with padding, is used when you need to get JSON data from an external domain. This is prohibited when using regular JSON due to possible security implications. You can read more on JSONP here. As it turns out, JSONP isn’t a special version of JSON, like I had originally thought. Instead, JSONP is a way to use cross-domain JSON data without having to worry about the browser preventing you from doing so. JSONP takes advantage of the fact that browsers don’t implement the Same-origin policy on script tags.
CORS, or Cross-Origin Resource Sharing, is another method that enables cross-domain JSON. For more nitty gritty details, checkout enable-cors.org.
CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed. CORS continues the spirit of the open web by bringing API access to all.
Simply put, if a server supports CORS, you don’t have to worry about the same-origin policy and you can make a standard JSON request. Here’s a demo that makes a request to the Github API, which supports CORS. If everything goes correctly, you should see URL that points to a Github issue. Note that this code is also jQuery free (I’m still on my jQuery fast).
Of course, not all browsers act the same, which means that sending a CORS request over any browser under IE10 means that a bit more code is involved. Telerik offers a great tutorial that explains how to write a function that supports CORS requests for IE8 and up.