Gettin’ Down with BaconIpsum

JSON

angular2 baconipsum json

Sometimes you need Lorem Ipsum, and sometimes you need it in json format via an API call. If you don’t mind bacon references spattered throughout that latin, then Bacon Ipsum can help.

I’ve already written an article about the need to make an API call before that service is ready. And myjson.com is a perfect tool for that. But if you just need a lot of text and want to generate it via an API, then Bacon Ipsum is a fun tool that can solve that problem.

The overall concept is a bit silly. I mean, lorem ipsum is kind of silly, and having words like  “bacon”, “flank” and “shankle” sprinkled throughout borders on nonsense. But their API works well and is very easy to use. So, if you are in the middle of a dev project and need some dummy text in JSON format, it’s nifty stuff.

Json API

The landing page allows you to generate some Bacon Ipsum on the fly, but if you want the API calls, then go to baconipsum.com/json-api. There  you’ve got very simple instructions on how to get your Bacon using simple query string parameters. These parameters allows you to control how many words and paragraphs will be returned.

Other Bacon-stuff

If you find this all funny and want more Bacon, they also offer a Chrome extension as well as Android and IOS apps that allow you to… well, I’m sure you can figure out what these do… more Bacon. Although I will note that these apps are pretty outdated, so use at your own risk. There is a jQuery plugin, and three.. count ’em three WordPress plugins for increased Bacon madness. And to top it all off: a baconmockup HTML generator. This might be a bit too much Bacon for me. They had me at the JSON API calls.

MyJson – An awesome tool for mock API calls

JSON

MyJson LogoSometimes you need to call an API that is not ready yet

So you are working on your front-end code. You have crafted you JavaScript so that it is clever and optimized. Check. You’ve created your “makeHttpRequest” method, and configured a success callback. Check. But there is one problem: the back-end team has not completed the API call that you have to make. Rats.

Sure, you can just create some static “dummy” data. But that is not the same thing as an HTTP request, and your code will not be asynchronous. Ok, so you could wrap your static data assignment in a setTimeout. Yeah, that’s it…. nah, just not the same thing as making a real HTTP request. Double rats.

myjson.com saves the day on this one.

This site is so dammed cool, I can’t get over it. You simply add some valid JSON into the large text area, and then click the “Save” button. You are then taken to a page that shows you two things: your JSON and a URL that you can use to make an HTTP request for your JSON. In other words, you just created your very own API call that returns the exact JSON that you need. Sorry folks, this one is better than the Beatles.

At first I was wondering: “…wait a minute. How can I make an HTTP request like this when myjson.com can not possibly have added my silly little test domain to their whitelist for the CORS header?” (yes, I actually talk to myself like this. it’s kind of scary). Well, after about five seconds in the network panel, I see “Access-Control-Allow-Origin: *” . Nice.

Examples:

I literally cannot even begin to imagine the countless hours this would have saved me in the past. Yeah, sure you can spin up something like this on your own, but good gosh; copy, paste, API! how much easier could this be.

Serious Kudos to whoever is behind this.

 

 

 

JSONP With Only Native JavaScript – Part I

JSON

JavaScript LogoMost front-end developers consume JSON at some point. It has become commonplace nowadays to fetch data from a cross-domain site and present that data in your page. JSON is lightweight, easy to consume and one of the best things to come along in a while.

Another one of the best things to come along has been this:

jQuery.getJSON()

jQuery makes fetching JSON trivial. And there ain’t nothin’ wrong with that. But it’s not a bad idea to have a solid understanding of exactly what is going on under the hood.

The big advantage of JSONP is that it allows data to be retrieved from any URL on the planet with no concern for the kind of cross-domain limitations of AJAX. So this means that we are taking advantage of one of the older features of the JavaScript language: the ability to inject a remote script into our page. In a nutshell, JSONP is accomplished via dynamic script injection. In other words, you create a script tag, set the ‘src’ attribute to be any script you like, and that script calls a function in your page, passing it some data.

Now in the real world, your remote script would likely be produced by an API that supports JSONP. In these cases you have probably seen the URL of JSONP call look something like this:

http://www.somedomain.com?callback=

This is a more sophisticated approach and will be covered in Part II. For now, however, we will keep things very simple. In order to do so, we have to have an agreement between our JSON file and our web page. Our web page has a function expression that makes that function available, and the JSON file knows to call that function.

First, let’s take a look at our JSON file.

Example # 1

Example # 1 is our JSON file. It is really just a JavaScript file. It consists of one function call: jsonpCallback(). The sole argument to this function call is an array of objects. Each object has two properties: ‘name’ and ‘accountNumber’.

We’ll come back to this file shortly. For now, it’s just important to focus on the fact that this is simply a JavaScript file that makes a function call, and passes an array to that function.

Example # 2

In Example # 2, we have the markup for our web page. Now there are two things happening here:

1) The function declaration jsonpCallback() might look familiar to you. This is the function that is called from our JavaScript file ‘data.js’. Notice that this function takes one argument: ‘data’. So it expects to receive some data. Inside the function we assume that the data came through and we inspect it in the console.

2) After the function declaration, we dynamically append a script to the head of the document. Now if you take a close look at the ‘src’ attribute of our script, you’ll see that it is ‘data.js’

Putting the pieces together

Now that we have the details laid out, let’s walk through the sequence of events:

  1. The page loads, and the function declaration for jsonpCallback() is evaluated
  2. jsonpCallback() now exists and can be called
  3. We dynamically append a script tag to the page
  4. The URL for this new script tag is data.js
  5. data.js is loaded and the code inside of it executed
  6. data.js calls the function jsonpCallback(), and passes it the array of data
  7. jsonpCallback() receives the data passed to it and we inspect it in the console

Again, this is an extremely rudimentary example. The focus here was to illustrate the core concepts in play: dynamic script injection and passing data to a function. In Part II, we will look at a more dynamic approach to JSONP.

Here is a link to the working example for this argument: http://examples.kevinchisholm.com/javascript/jsonp/example-1/

Summary

In this article we learned how to implement JSONP using only native JavaScript. We discussed how the script that we dynamically inject into the page calls a function, passing data into the function that it calls.

Helpful Links for JSONP

http://en.wikipedia.org/wiki/JSONP

http://json-p.org/

http://remysharp.com/2007/10/08/what-is-jsonp/

Problems Making JSONP Calls in JSFiddle

JSON

JSFiddle Logo
If you are pulling your hair out while trying to demo a JSONP call with JSFiddle, don’t bother. It won’t work out of the box.

There is no doubt that JSFiddle is a super-useful tool for saving little demos that you can share with others.  I use it like crazy when providing simple demos in this blog. Tons of cool features and in general, a brilliant idea.

One little quirk I ran into this morning is JSONP calls. I’m writing Part II of a post called: “Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object”. In this second part, I introduce the tricky scenario of adding a JSONP call as a dependency, which is in addition to other dependencies that are multiple asynchronous  JavaScript calls that may (or may not) have already loaded in the page (I know, I know….. I need to get a life).

Anyhooooo….

When attempting the code in example # 1, I got the following error: “myCallback is not defined”.

Example # 1

My guess is that JSFiddle uses iframes to render your test code. I’ve not made any attempt to look into this further, and I’m sure the answer is likely a call to “parent” or something similar. But just in you are pulling your hair out trying to demo a JSONP call using JSFiddle, hopefully this will save you the 20 minutes of troubleshooting that I just did. It won’t work out of the box (again, probably due to the use of iFrames). When I figure out the answer, I will post it. I’ll try to look into it this weekend.

Kevin