Introduction to AJAX and JSON



Introduction to AJAX and JSON

0 0


ac-intro-to-ajax

Class slides http://anniecannons.github.io/ac-intro-to-ajax

On Github AnnieCannons / ac-intro-to-ajax

Introduction to AJAX and JSON

Note: We're not using an API in this class, we're just going over the concept of AJAX.

Let's Review

How do JavaScript and HTML work together?

Static Content and Progressive Enhancement Dynamic Content

1) Static Content + Progressive Enhancement

  • Progressive enhancement uses web technologies in a layered fashion that allows everyone to access the basic content and functionality of a web page, using any browser or Internet connection

1) Static Content + Progressive Enhancement

This also provides an enhanced version of the page to those with more advanced browser software or greater bandwidth.

1)Static Content + Progressive Enhancement

Example

2) Dynamic Content

Adding Data (often user data)!

Using JavaScript to turn JSON into DOM

JSON = JavaScript Object Notation

  • JSON is all about transmitting data objects
  • This is a way to store data!

How does JSON work?

  • Using Key/Value pairs
  • Keys must be stored with quotes (unlike JS Objects)
  • Value can be the following data types: Number, String, Boolean, Array, Object, null
  • Resembles objects in JS
  • Validate @ JSONLint.com

Example

{
 "firstName": "Jane", 
 "lastName": "Smith", 
 "address": { 
   "streetAddress": "425 2nd Street", 
   "city": "San Francisco", 
   "state": "CA", 
   "postalCode": 94107 
 }, 
 "phoneNumbers": [ 
   "212 732-1234", 
   "646 123-4567" ] 
} 
            

Example 2

var myProfile = 
 {"firstName": "Liz", 
  "lastName": "Howard",
  "cats": ["Tribbles", "Jean Claws"]};

var p = document.createElement('p');
p.innerHTML = 'My name is ' + 
myProfile.firstName + ' ' + myProfile.lastName + '. ';
p.innerHTML += 'My cats are ' + 
myProfile.cats.join(', ') + '.';


var p = $('<p>');
p.html('My name is ' + myProfile.firstName + ' ' +
 myProfile.lastName + '. ');
p.append('My cats are ' + myProfile.cats.join(', ') + '.');
            

Exercise Time!

Follow this link

What does asynchronous mean?

Asynchronous technologies enable users to access information or communicate at different points of time, usually at the time of choice of the user.

The traditional data-driven web application is written so that it:

Displays a webpage Waits for user interaction Asks the server for data Reloads the webpage

Sad Users

This has the effect that the user has "down time" - there is a period of time where they can't interact with the webpage at all

AJAX

AJAX = "Asynchronous JavaScript and XML."

  • AJAX is a technique for creating fast and dynamic web pages.
  • You can update parts of your web page, without reloading the whole page!
  • Examples of applications using AJAX: Google Maps, Gmail, YouTube, and Facebook.

AJAX

  • Allows for asynchronous data transfer between a webpage and a web server.
  • Javascript tells the browser to retrieve a particular URL and send the data back to the webpage.

Let's talk about this diagram

AJAX in the Wild

What else?

Web 1.0 and User Interaction

Web 2.0 and User Interaction

Importance of AJAX for Web 2.0 Programming

  • The user can still interact with other parts of the page while one part is loading.
  • The user can selectively load the content they're interested in.
  • This is arguably the most important part of Web 2.0 programming!

Web 1.0 vs. Web 2.0

Technologies Used: Technologies Used:
  • HTML
  • Server-Side Scripts
  • HTML
  • Server-Side Scripts
  • AJAX

Requests and Responses

Requests and Responses

  • Front-End: Hey, Back-End! Here's my credentials. Can I get some data? How about books on AJAX?
  • Back-End thinks about it, decides how to handle request...looks in database, searches...
  • Back-End: 200 OK, here are some books on AJAX!
  • Front-End: Thanks! I'm going to make an online bookshelf with the data!

How does this communicating take place?

XMLHttpRequest

XMLHttpRequest (XHR) is an API (woohoo!) available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script.

Anatomy of an XMLHttpRequest

// instantiate a new request
var request = new XMLHttpRequest(); 

// add event listeners
request.addEventListener('load', function () {

  // transform a string into a usable object
  console.log(JSON.parse(request.responseText));
});

request.open('get', '/path/to/api', true);
request.setRequestHeader('Content-type', 'application/json');
request.send();
            

BUT! We don't need to write all that code...

jQuery and AJAX

We can use the jQuery $.ajax function.

$.ajax({type: "GET",
  url: "filename.json",
  dataType: "json",
  success: function(data) { },
  error: function(xhr, status, e) { }
});    
            

Using jQuery for everything

$.ajax({type: "GET",
  url: "books.json",
  dataType: "json",
  success: function(books) { 
    for (var i = 0; i < books.length; i++) { 
      var book = books[i];
      var p = $('<p>');
      p.html(book.title + ' by ' + book.author);
      $('body').append(p);
    }
  },
  error: function(xhr, status, e) {
    console.log(status, e);
  }
});
            

Remember!

jQuery is just a library, written by human beings. Use it because it saves you time, but don't rely too hard on it!

Debugging AJAX Requests

  • Click the NET/Network tab in Chrome Dev Tools or Firebug, select "XHR" filter to see all XMLHttpRequests made.
  • See what the request responded with by clicking its "Response" tab.
  • Explore this tab! It will teach you so much about what's in requests and responses. (Google everything you don't understand.)
  • Visit this link again.

Exercise Time!

Follow this link

AJAX + Servers

Looking at "GET" and "POST"

$.ajax({type: "GET",
  url: "/api/books",
  dataType: "json",
  data: {'sortBy': 'author'},
  success: processBooks
});

$.ajax({type: "POST",
  url: "/api/book/new",
  dataType: "json",
  data: {'title': 'I, Robot', 'author': 'I. Asimov'}
  success: processBoooks
});
            

Cross Domain Policy

  • The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.
  • It is a critical security mechanism for isolating potentially malicious documents.
  • Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages. The following table gives examples of origin comparisons:

Cross Domain Policy

For http://store.company.com/dir/page.html:

Important AJAX Reminders

  • Cross domain requests have restrictions
  • Multiple AJAX requests don't return in order
  • Hard to transfer files
  • Browsers can over-cache/under-cache requests
  • Can't transfer binary content

Example using an API

We will check out this example using Meetup's API Click here

What is happening?

(Let's add the Chrome extension JSON formatter)

Let's display the data!

$.ajax({
type:"GET",
url:"https://api.meetup.com/2/cities",
success: function(data) {
  $('.text').html('');
  for (var i = 0; i < data.results.length; i++){
  var place = data.results[i].city + "," + 
  data.results[i].state;
  $(".text").append("

" + place + "

"): }},

What happens?

Another exercise

Click here

List of additional key concepts

  • What are the parts of an HTTP request?
  • What does CRUD stand for?
  • What is the same origin policy?
  • What are the 4 basic CRUD operations and methods?
  • What is the difference between JSONP and JSON?

THE END

Thank you for your attention!

Introduction to AJAX and JSON Note: We're not using an API in this class, we're just going over the concept of AJAX.