Civic Hacking with the Consumer Complaint Database API

Set up a local development server.

Easiest (Python, installed on Mac OSX)

Windows IIS

Very detailed (Apache)

Long list of simple-setup servers

Let's take no more than 10 minutes to try and get this set up, but again, we can use [CodePen](http://codepen.io), so don't worry if you can't get a dev server up and running.

AJAX: Asynchronous JavaScript And XML

Normally, the rendering of a web page is a relatively sequential process from the top of the file to the bottom.

With AJAX, we use JavaScript to request additional data outside the normal page-load process, often long after the initial load is complete.

AJAX: Where is it used?

Synchronous vs Asynchronous

These are the main differences between synchronous and asynchronous processes:

Synchronous
  • tasks occur strictly in sequence
  • easy to understand, predict, manage
  • only possible with simple scripts
  • sometimes referred to as "blocking"
Asynchronous
  • order of tasks may have gaps in it
  • multiple processes can be interleaved
  • can result in "race conditions"
  • callbacks and timeouts are good indicators

What do these gaps look like?

When you submit a purchase and the page tells you not to refresh or hit the back button. Then it takes you to the confirmation page.

XML: Extensible Markup Language

XML is a markup language and file format used to store and transmit data. It is extremely flexible: XHTML is a subset of XML.

sample of XML

AJAX and XML

AJAX was originally developed for use with XML, but you can use it to request many different things. Most often JSON or HTML.

JSON: JavaScript Object Notation

JSON is a newer, popular file format for storing and transmitting data. It looks like and translates easily into JS objects! It requires less markup than XML, and has a less formal feel.

sample of JSON

Let's Develop It!


var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsonplaceholder.typicode.com/users/2/');
    
  1. Create the request object
  2. Set some details of the request, like the type of request (GET) and the URL to ask for

xhr.send(null);
    
  1. Send the request


Open the page in Google Chrome or another web browser that has Developer Tools and check the "Resources" panel in the Chrome Developer Tools to see if it worked.

Wooo!

kitty!

Handling the response

We know we're getting data back! Now what?


xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
// Soon, we'll replace this with a callback!
console.log(xhr.responseText);
} else {
// An error occurred during the request.
console.log('Error: ' + xhr.status);
}
}
};
xhr.send(null);
    

AJAX Concerns

AJAX is great for all the things we've been discussing, but what are some possible risks?

CORS: Cross-Origin Resource Sharing

At the server-level, the admin can specify what types of requests to permit. Today, we're using APIs that allow CORS, but in other cases, you might need to use an alternate technique that relies on JSONP.

A pretty straightforward explanation

Break time!

This is not bad...


var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsonplaceholder.typicode.com/users/2/');
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status);
}
}
};
    

But what about this?


$.ajax({
url: 'http://jsonplaceholder.typicode.com/users/2/',
}).done(function(res) {
console.log(res);
}).fail(function(err) {
console.log('Error: ' + err.status);
});
    

jQuery

A library of JS functions and features designed to make the life of a JS developer much easier, especially when it comes to accommodating differences between browsers.

jQuery is written in JavaScript, so anything done in jQuery can be done in JavaScript, it just might be a lot of work.

It is also just as difficult to use as "vanilla" or "raw" JS, if you don't understand the underlying process.

Compare

Vanilla JS


var content = document.getElementById('content');
var contentDivs = content.getElementsByTagName('div');
for (i = 0; i < contentDivs.length; i++) {
contentDivs[i].style.display = none;
}
    

jQuery


$('#content div').hide();
    

However, AJAX is one place jQuery really shines...

Vanilla JS


var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsonplaceholder.typicode.com/users/2/');
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status);
}
}
};
    

jQuery


$.ajax({
url: 'http://jsonplaceholder.typicode.com/users/2/',
}).done(function(res) {
console.log(res);
}).fail(function(err) {
console.log('Error: ' + err.status);
});
    

But that's a topic for another day.

Let's Develop It!

Let's modify the success case in our AJAX request to call a function and pass in the response text.


var onSuccess = function(response) {
console.log(response);
};
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      onSuccess(xhr.responseText);
    } else {
      console.log('Error: ' + xhr.status);
    }
  }
};
    

Now try to log the name of the returned user.

Now try to log the typeof the result.

What's going on?

It looks like an object, but it's actually a string.

This is one of the perks of JSON.

Objects as Strings

Remeber that JSON is a kind of "object notation." It allows us to pass around objects as strings, which can then be converted back into objects.

Stringify & Parse

JSON.stringify() allows us to convert objects into strings.

JSON.parse() allows us to convert strings into objects.

Let's Develop It

Convert the response text into an object we can work with, and log the name of the returned user.


var onSuccess = function(response) {
var responseObj = response && JSON.parse(response);
console.log(responseObj && responseObj.name);
};