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.

 

 

 

What Are the Top 10 JavaScript Links for AJAX ?

AJAX

AJAX Logo

Over the years I’ve amassed a list of web sites that have strong content about AJAX. Iv’e managed to whittle it down to ten.

This list will change often.


Ajaxian

Ajaxian.com

Other than having a domain that clearly indicates a focus on AJAX, this site offers create content about not only AJAX, but also other web-development technologies.


AJAX | MDN

developer.mozilla.org/en-US/docs/AJAX

Mozilla Developer Network’s introductory page on AJAX is a portal to some of the best content on AJAX out there.


XMLHttpRequest – Web API reference | MDN

developer.mozilla.org

AJAX ain’t nothin’ without the XMLHttpRequest. As usual, Mozilla Developer Network provides a high-quality article on the subject.


Ajax | jQuery Learning Center

learn.jquery.com/ajax

Although I am a believer that any front-end developer should have a strong understanding of AJAX in the context of native JavaScript, this site is a fantastic resource from the folks at jQuery.


Ajax Tutorial for Beginners: Part 1 – CodeProject

codeproject.com

A little old, but a solid article on AJAX from the good folks at The Code Project


The Best Way to Learn JavaScript | Nettuts+

tutsplus.com

Nettuts+ is always a great resource for front-end web development advice. Here they offer guidance on how to get started with AJAX.


Microsoft Ajax Overview

msdn.microsoft.com

It’s from Microsoft, but it’s not a bad article : – )


Ajax : The Official Microsoft ASP.NET Site

asp.net/ajax

If you are a .NET developer, this is a great launch point for .NET specific AJAX content.


A Beginner’s Guide to Using AJAX in Your Website

onextrapixel.com

This article from onextrapixel.com is a good read if you are completely new to the concept of AJAX.


Ajax: A New Approach to Web Applications – Adaptive Path

http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications

This link is not so much a tutorial, but it is the the article that started it all. Jesse James Garrett’s original post that got everyone talking and made the XMLHttpRequest object a rock star.

Using jQuery Deferred to Manage Multiple AJAX calls

jQuery

jQuery LogoOnce you have become accustomed to making AJAX calls and consuming the contents of the data returned by the server, it is tempting to fall into a laid-back mind set: “hey, AJAX is AJAX right?… I mean… you open the request, you send the request, you wait for the server’s response, and then you do something with the response… no big deal, right?”

Well, yes, but… because of the asynchronous nature of an AJAX call, it does not take long for more complex scenarios to arise. What happens when you need to know about a group of AJAX calls? How can we treat a series of asynchronous events as a single value that we need to act upon once there is a collective “success” value?

Enter the jQuery.when() method. This handy dandy little tool allows you to treat multiple asynchronous events as a single value. The syntax is quite simple:

var B = $.get(serverPage.xyz); var C = $.get(serverPage.xyz); $.when(A,B,C).done(funtion(){ //act upon the collective success of A,B and C });

Some might find this a bit unusual. Normally, an AJAX call is something you simply “do,” not something you assign to a variable. jQuery allows us to treat an AJAX call as a value. This value translates to an object that has properties and methods. The $.when() method knows how to recognize and act upon these objects, so it presents a perfect way to handle multiple asynchronous events as a single value.

Example # 1

In Example # 1, we create the variable “aj1”, and set it to equal the result of an AJAX call. This variable becomes a jQuery “jqXHR” object. When we immediately inspect the object, we see that it has a number of methods. This is interesting, but not super interesting.

If you open your JavaScript console and then run this code, you will see the AJAX call in progress, and the contents of the jQuery “jqXHR” object. But if you wait a few seconds, and then after the AJAX call completes, you once again run the code: console.dir(aj1), you will see that this object has changed a bit. The “readyState” property is equal to 4, the “responseText” property contains some HTML from the server, the “status” property is equal to 200, and the statusText is: “OK”. Because the AJAX request has completed, this jqXHR object has properties that reflect this new state.

Example # 2

In Example # 2, we use the jQuery.when() method to act upon the completed state of the AJAX request. When using this syntax, the completed state of each request is a corresponding argument in the anonymous function that is passed to the .done() method. Now we have something interesting, because what we see is that each one of these success objects is an array. The first element is the response text of the request, the second element is the status of the request, and the third element is the original “jqXHR” object.

Example # 3

In Example # 3, we set up three AJAX calls. Normally, one might create a success handler for each AJAX call. In this case, we simply want to know when all three calls have completed successfully. We pass all three AJAX calls (i.e. the three variables that have been assigned the return value of each AJAX call), as arguments to the .when() method. Then we pass an anonymous function to the .done() method that is chained to the .when() method’s return value.

Just as with Example # 2, we take the success object for each call as the corresponding argument of the .done() method call. Inside of the .done() method’s callback, we take action; the contents of the $(‘#target’) element is removed, and we append the server response messages to that element.

Here is the full working example: http://examples.kevinchisholm.com/jquery/when/example-1/

Summary

If you have not had to wrestle with a scenario like this, you soon will. You’ll find that as web pages become more complex, AJAX is leveraged in more complex ways. When asynchronous activity is involved, any complexity is magnified. So, fortunately, the jQuery.when() method is an easy and effective way to handle multiple AJAX calls as one collective value.

Helpful Links for the jQuery.when() method

http://api.jquery.com/jQuery.when/

http://api.jquery.com/category/deferred-object/

http://stackoverflow.com/questions/5280699/jquery-when-understanding

 

Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom

jQuery

jQuery LogoNested success callbacks are messy business. The jQuery Promise interface provides a simple and elegant solution.

So, you have to make an AJAX call, and then do something with the return data. No problem, right? Right. What if you have to make two AJAX calls, and then do something with the return data for each one? No problem, right? Right. What if the second AJAX call depends on the success of the first AJAX call?

“…um, well…. then, well… wait a minute… ok, I’ve got it:

I’ll make the first AJAX call…and then inside the success callback function, cache the data somewhere… um… in a global variable for now I guess… yeah, no one will notice. OK, and then inside of that success callback, we’ll nest another AJAX call, and then inside of the second AJAX calls’ success callback, we’ll get our first chunk of data from the global variable, and then, and then… um…and then…”

…yikes!

Obviously, the preceding diatribe was a little over the top, but c’mon…. haven’t you at least once stood at the edge of that cliff and looked over? Fortunately, jQuery features a way out of this mess that is safe, reliable and packed with vitamins.

The jqXHR object

Since version 1.5.1, jqXHR objects returned by $.ajax() implement a “Promise” interface. In short, this means that a number of methods that are exposed provide powerful abstraction for handling multiple asynchronous tasks.

I think it is important to note that the subject of the jQuery Deferred and Promise Objects is deep. It is not an easy topic to jump into and a detailed discussion of this is outside of the scope of this article. What I hope to accomplish here is to provide a simple and fast introduction to the topic, by using a real-world problem / solution.

There are certainly multiple scenarios in which the jQuery Deferred and Promise objects can be useful. I have chosen to use AJAX calls for this, since it is an example of asynchronous behavior that I think most folks can relate to. In order to dramatize the effect of an asynchronous AJAX call, I am using a PHP file that can return a delayed response. Here is the code for the server page:

OK, now some AJAX.

(Note: I highly recommend that you open up the “network”  panel in Firebug or WebKit developer tools so that you can see these AJAX calls in action when viewing the working examples… especially AJAX call # 1, which will take 5 seconds to complete)

Example # 1

In Example # 1 we have a fairly straightforward setup: Two buttons, each resulting in an AJAX call. Notice that the 1st AJAX call takes 5 seconds to complete. Instead of providing an inline anonymous function for the success callback of each AJAX call, we have a generic handler named “success”.

Here is a link to the working code for Example # 1: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-1.html

But what if we want AJAX call # 2 to depend on AJAX call # 1? That is, we don’t want AJAX call # 2 to even be possible until AJAX call # 1 has completed successfully.

Example # 2

In Example # 2, we have a pattern that is known as the “Pyramid of Doom”. This might work for the short term, but it is impractical, not at all flexible, and just plain messy. What if there was a third button, and a fourth button… I think you see what I’m getting at here.

Example # 3

Ahhh… that’s much better!

In Example # 3, we have taken advantage of the Promise interface that is exposed as part of the jqXHR object. If you are wondering what the jqXHR object is, it is the return value of any $.ajax() call. So, while you can simply do this: $.ajax(URL,CALLBACK), the call itself returns a value. That return value is the jqXHR object, which is a superset of the XMLHTTPRequest object.

The return value of $.ajax() is the jqXHR object, which is a superset of the XMLHTTPRequest object, and packed with some powerful features.

We don’t have to dive too deeply into the good ol’ XMLHTTPRequest object (although it is important to know what it is and the critical role that it plays in AJAX). But the key point here is that the jqXHR object wraps the XMLHTTPRequest object, providing some useful features. One of those features is the “Promise” interface.

“….ok, ok Kevin, you’re givin’ me a migraine… where are you going with all this?”

Hang in there; we are at the 99 yard line here. What this all means is that instead of just making an AJAX call, you can assign that AJAX call to a variable. Since the $.ajax() method returns the jqXHR object, your variable is now a Swiss Army knife of AJAXian goodness. You can then implement methods of your object (i.e. your variable). Two of those methods are: .when() and .done();

So, in Example # 3, when we fired the first AJAX call, we assigned its return value to the variable “aj1”. Notice that we did NOT make a success handler call. We simply make the AJAX call, and that call’s return value is held by the variable “aj1”. Then when the user clicks the second button. we set the return value of the second AJAX call to the variable: “aj2”. Now we have two variables and each is a jqXHR object. These are powerful little objects!

The line where the fun really starts is: $.when(aj1,aj2).done()

Notice how the .done() function takes a callback. The callback is fired when the two arguments passed to the .when() method are resolved. And guess what those two arguments are… our two little jqXHR objects!

So, the .done() method knows how to get ahold of the data returned by each of those calls. Now we simply call our generic success handler, passing in the return data of each AJAX call (i.e. each jqXHR object). You may be wondering why I pass in the values “a[0]” and “b[0]”. This is because “a” and “b” are jqXHR objects. It just so happens that the first property of these objects (i.e. the property with the index of 0) happens to be the “responseText” property of that object (i.e. the text sent back from the server).

Phew!

I know that was a lot. But there is much to shout about when it comes to the jQuery Promise interface. As I mentioned, it is a big topic and not easily summarized. But my hope is that these examples will have put a little context around the subject, and will help you to dive in and get started.

Below is the source code for this article’s full working example:

Example # 4:

Here is a link to this article’s full working example: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-2.html

Summary

In this article we learned about the jQuery Promise interface. We discovered that since version 1.5.1, calls to $.ajax() return a jqXHR object, which implements the Promise interface. We utilized the .when() and .done() methods of this interface to execute callback functions for two asynchronous tasks. This eliminates the need for nested success callback functions.

Helpful Links for the jQuery Deferred, jQuery Promise and jqXHR Objects

jQuery Deferred

http://api.jquery.com/category/deferred-object/

http://api.jquery.com/jQuery.Deferred/

jQuery Promise

http://api.jquery.com/promise/

http://api.jquery.com/deferred.promise/

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

jQuery jqXHR

http://api.jquery.com/Types/#jqXHR

http://api.jquery.com/jQuery.ajax/#jqXHR

Hand-Coded JavaScript AJAX – The Absolute Basics

AJAX

JavaScript LogoUnderstanding the basic components of an AJAX request / response, and being able to write it all out by hand is an important skill for any JavaScript developer to have.

Yeah yeah yeah, you’ve used jQuery.ajax(). But can you write AJAX code by hand, starting with a blank sheet of paper? While some might feel that jQuery, DoJo and other popular libraries abstract these kinds of details just fine, it’s important to understand what is happening under the hood.  So, give me a moment to step down from my soapbox.js and let’s jump into the code.

The XMLHttpRequest Object

The XMLHttpRequest object is the key to AJAX. It is a constructor function that is a property of the window object. You instantiate this object, and then take advantage of the various properties and methods of the instance object that is returned.

Determining Support for the XMLHttpRequest object

Previous to Internet Explorer version # 8, there was no support for the native XMLHttpRequest object. You had to instantiate IE’s ActiveXObject(), and pass in the argument: “Microsoft.XMLHTTP”. Even though the IE6 and below audience is dwindling, someone out there is still using IE6 or IE5, so it’s a good idea to handle that scenario gracefully.

Example # 1

In Example # 1, we use an IF/ELSE block to determine support for the XMLHttpRequest object. If it is supported, we instantiate the object and if not, we instantiate IE’s native ActiveXObject object.

The onreadystatechange Event

Of the eight events fired by the XMLHttpRequest object, the one we tend to care about most is the onreadystatechange event. It indicates the “readiness” of the XMLHttpRequest object’s request. A ready state of four (4), indicates that the XMLHttpRequest object’s request has generated a response, and that response is in the browser, and ready to be consumed.

The status Property

XMLHttpRequest object’s “status” property represents the HTTP status code returned by the server when our XMLHttpRequest object’s request was sent. There are numerous HTTP status codes that can be returned by a web server, but a detailed discussion of them is outside of the scope of this article. Simply put, we are most often only interested in an HTTP status code of “200” which means: “ok”. It is the web server’s way of saying: “I have completed your request, here it is, and there were no problems”.

So, the combination of an XMLHttpRequest object readystate of 4, and HTTP response code of 200 is the scenario we want. This scenario means that our request was returned, it is ready and there was no problem with the request. Once we know that this condition exists, then we can do something with whatever was returned by the XMLHttpRequest object’s response request.

req.onreadystatechange = function(){ if (req.readyState === 4 && req.status === 200){ //if readyState is “4” and the server response was 200/ok… //inject the returned HTML into the DOM document.getElementById(‘target’).innerHTML = req.responseText; }; };

Opening the XMLHttpRequest Object’s Request

So far, nothing has happened. All we have done is instantiate the XMLHttpRequest object, and set up a function that will execute when we know that the request’s response is “ready” and there was no problem with the request. Now we will open the request.

When calling the open() method of the XMLHttpRequest object, we pass in three arguments:

  • The type of request (“GET” or “POST”)
  • The URL that the request should be set to
  • If the request should be sent asynchronously (you will almost always want this to be “true”)

Sending the XMLHttpRequest Object’s Request

So this is the final step in writing an AJAX call: sending the request. There is nothing more to do than simply execute the .send() method:

Now let’s look at the markup we’ll need for the article’s example. Below you’ll see two buttons. One will kick off the AJAX request, and the other simply clears the contents of the page. There is also a DIV with an id of “target”. That is the element in which our AJAX request’s response text is injected.

We also have some JavaScript that sets up event handlers for the button clicks. When clicking the button with the ID of “click”, the AJAX request is kicked off and the requests response text is injected into the DIV with the ID of “target”. When clicking the button with the ID of “clear”, the “target” DIV’s contents are cleared.

It is not critical to be aware of the server page’s code for this very simple example, but in case you are interested, it is a simple PHP page that sends a message that includes the time of the request, allowing us to verify that the requests are being made in real time.

Server Code

Below is the full working code for our AJAX eample:

Example # 2

Here is a link to the full working page for this article’s example:

http://examples.kevinchisholm.com/ajax/example-1/

Summary

In this article we discussed the XMLHttpRequest object. We learned how to test for the browsers support of this object, instantiate it and assign an anonymous function to handle its onreadystatechange event. Inside of that function, we learned how to check for the readyState property value, the status property and then inject the return text into the DOM. We also discussed how to open the XMLHttpRequest object’s request, and then send it.

Hand-coded AJAX is no big deal, and I’m hoping that this article has left you feeling this way. The key is getting to know the XMLHttpRequest object, specifically its various properties and methods. There is plenty more to talk about with regard to AJAX in native JavaScript, but what we covered in this article is the bare minimum needed to get up and runing.

Helpful Links for hand-coded AJAX

What’s the difference between jQuery.ajax(), jQuery.get() and jQuery.post()?
Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom
Using jQuery Deferred to Manage Multiple AJAX calls
What Are the Top 10 JavaScript Links for AJAX ?

What’s the difference between jQuery.ajax(), jQuery.get() and jQuery.post()?

jQuery

jQuery LogojQuery offers three Ajax calls that are simple and painless

Although it is a good idea to understand Ajax in the context of native JavaScript, leveraging the power of JavaScript libraries for your Ajax calls is not a bad idea. Depending on the size and complexity of your application, it can often minimize the amount of code you need to write in order to provide the best cross-browser experience.

Question: “What is the difference between jQuery.ajax(), jQuery.get() and jQuery.post() ?”

Answer: jQuery.get() and jQuery.post() contain features that are subsets of jQuery.ajax().

So jQuery.ajax() is the method that provides the most flexibility of the three. You’ll see that the biggest difference from an implementation standpoint is that you pass an object to jQuery.ajax(), which contains the necessary parameters. And as for jQuery.get() and jQuery.post(), here you pass in arguments. So you might say that jQuery.get() and jQuery.post() are both shorthand for jQuery.ajax().

Important Note: Because of the “Same origin policy” enforced by all browsers, I could not make a jsfiddle example for this post. But you can copy and paste these code examples into a simple html file, and just make sure that is a file named test.txt in the same folder. Put a simple message in that text file (i.e. “hello from the text file”).

jQuery.ajax()

Example # 1

So, in Example # 1, we use the jQuery.ajax() method. There are certainly more configurable parameters, but here we are using the bare minimum.

You’ll see that there is not much going on here. We just pass an object into the jQuery.ajax() method. That object has four properties: “url,” “dataType,” “type,”  and “success”, and here are the details for each property:

  • url: This is the URL of the file that you want to grab via your ajax call.
  • dataType: This determines how the return data will be treated (i.e. pure text, html, XML, etc.).
  • type: This the the request type. Choose “GET” or “POST”. This is actually optional; if you omit it, jQuery will default to “GET”.
  • success: This is a callback function that is fired after a successful http request has completed. The first argument to the function is the data returned from the server. There are other arguments that can be passed in as well.

As long as you have a file named “test.txt” that has some kind of message, and it is in the same folder as your html file, the contents of that text file will appear in your JavaScript console. (Don’t forget to open the console! : – ). Of course, you can put that file anywhere you want, as long as it is on the same domain as the requesting file.

A video tutorial, explaining the difference between jQuery.ajax(), jQuery.get() and jQuery.post()

Here, in this video, I briefly explain the difference between these three AJAX utilities. You’ll see that I demonstrate how jQuery.get() and jQuery.post() are very similar, and how jQuery.AJAX is a more generalized method that allows you to make either GET or POST AJAX requests.

jQuery.get()

Example # 2

Now here, in Example # 2, we use the .get() method, which is a kind of shorthand for jQuery.ajax(). When using jQuery.get(), instead of passing in an object, you pass in arguments. At minium, you’ll need the first two arguments: the URL of the file you want to retrieve (i.e. ‘test.txt’), and a success callback. In this example, we also passed in a third argument: ‘text,’ which told jQuery that we wanted to treat the return message as text.

The jQuery.get() method is recommended when you want to make a quick and dirty Ajax call and you are sure it will be a GET. So here, there’s not much more to it. Short and sweet.

jQuery.post()

Example # 3

And finally, in Example # 3, we used jQuery.post(). And in exactly the same manner as jQuery.get(), this method is like using jQuery.ajax(), and specifying a “type” of “POST.” So, this method is recommended if you need to make a quick Ajax call via POST, and don’t need to make a lot of configuration decisions.

What About Multiple AJAX Calls?

When you have code that depends on the mutual success of multiple Ajax calls, things can get messy. Quite often, a developer might implement an AJAX call inside the success function of another one. This can work, but what if there is a total of three AJAX calls? or even four? Well, what you wind up with is a pattern called the “Pyramid of Doom”:

The Pyramid of Doom is a JavaScript anti-pattern that should be avoided. If you are already using jQuery, you can leverage the power of the jQuery.when() method, which can be leveraged to treat multiple AJAX calls as one asyncronous event:

To learn more  about using the jQuery.when() method to manage multiple AJAX calls in JavaScript, you can read these posts:

http://blog.kevinchisholm.com/javascript/jquery/using-jquery-deferred-to-manage-multiple-ajax-calls/

http://blog.kevinchisholm.com/javascript/jquery/using-the-jquery-promise-interface-to-avoid-the-ajax-pyramid-of-doom/

Summary

If you are wondering whether you should use jQuery.ajax(), jQuery.get() or jQuery.post(), it is really up to you. One way to approach it might be to ask yourself: “Am I writing a multi-purpose function that will be able to perform either a GET or a POST? And I do I want this function to accommodate dynamic settings such as dataType or data?” If the answer to these questions is “yes,” then use jQuery.ajax(), and wrap it with your own custom function that takes an object as an argument. If you are thinking “nah, I just need to make a quick GET or POST Ajax call, then get the data, do something with it, and use jQuiery.get() or jQuery.post().

Helpful Links for jQuery.ajax(), jQuery.get() and jQuery.post()

http://api.jquery.com/jQuery.ajax/

http://www.w3schools.com/jquery/jquery_ref_ajax.asp

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/