Front End Web Development

Spark Boulder, Summer 2017

Session 16: Revenge of the Session

jQuery 202: jQuery advanced methods, HTTP requests with jQuery - Part 1

THE END IS NIGH

We're approaching the end of the class!

On August 23rd at 9pm (1 week after the class ends), report cards get generated!

Report cards include grades on all assignments, attendance, and links to projects:

Remember to check your grades with grades on @classbot!

Remember to create separate site44 apps for your projects so that potential clients and employers can see them!

The Social Network Front End Project

For your final project, I'm going to have you create the front end to the Spark Front End Web Development Social Network.

All of the students in the class are on the Social Network! You can create new posts, and everyone else in the Social Network can see those posts.

For your front end, you'll need at least 2 pages:

You'll need to make requests to the API to create and get posts on the Social Network. All of the API documentation is up at https://spark-class-social-network-api.hoff.tech/.

Some notes:

Logistics:

More Dumb Fun Web Stuff

ACTIVATE POWER MODE

https://atom.io/packages/activate-power-mode

Tonight

jQuery advanced methods and HTTP requests!

More jQuery methods: .click()

You can listen for clicks on elements pretty easily with jQuery!

The .click() method takes one argument, a function.

<!-- index.html -->

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    </head>
    <body>
        <button class="profoundButton">Tell me something profound</button>
        <script src="myscript.js"></script>
    </body>
</html>
// myscript.js

$(".profoundButton").click(function () {
    alert("Fur pillows are hard to actually sleep on.");
});

What if I had more than one button with the class of profoundButton?

More jQuery methods: .hide() and .show()

The .hide() and .show() methods use CSS to hide and show stuff!

<!-- index.html -->

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    </head>
    <body>
        <p class="quote">
            Fur pillows are hard to actually sleep on.
        </p>
        <button class="showButton">Show me a quote!</button>
        <button class="hideButton">I don't want to see that quote anymore, hide it!</button>
        <script src="myscript.js"></script>
    </body>
</html>
// myscript.js

$(".quote").hide();
$(".showButton").click(function() {
    $(".quote").show();
});
$(".hideButton").click(function() {
    $(".quote").hide();
});

What CSS styles do .hide() and .show() apply?

Creating new HTML elements with jQuery

You can create elements by passing an HTML string instead of a selector string to $:

$( "<p>Test</p>" ).appendTo( ".inner" );

Ken's recommendation: use .appendTo() (http://api.jquery.com/appendTo/). You can try using .add(), but I've never been any good at figuring out which is the source and which is the target.

HTTP Requests

HTTP stands for Hypertext Transfer Protocol.

Every time a client (your computer) needs to get something from a server, it sends the server something called an HTTP Request.

Then, the server sends an HTTP Response back.

HTTP Requests - Advanced

Here's a couple situations in which HTTP requests and responses are used:

I'm abstracting a lot here - HTTP actually runs "on top of" another protocol called TCP/IP.

TCP/IP takes a bunch of data, separates it into chunks, converts it into the 1s and 0s needed to send it over the wire to the other computer.

For the ultra-curious, here's what an HTTP request from a client to a server looks like:

GET /index.html HTTP/1.1
Host: www.example.com

And here's what the server would send back to the client:

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close

<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>

The two popular types of HTTP requests

The two main types of HTTP requests are GET requests and POST requests.

We use GET requests whenever we want to read data:

We use POST requests whenever we want to write or submit data.

There are a bunch more "verbs" besides GET and POST, like PATCH, PUT, and DELETE. Sometimes you'll hear about OPTIONS or HEAD.

Sending HTTP GET requests with jQuery's $.ajax()

(I'll talk about what "AJAX" actually is in just a minute)

jQuery's $.ajax() documentation: http://api.jquery.com/jquery.ajax/

Notice that we just use $, not $()!

Let's try just getting the HTML of https://spark-class-social-network-api.hoff.tech/ right now:

<!-- index.html -->

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    </head>
    <body>
        <script src="myscript.js"></script>
    </body>
</html>
// myscript.js

$.get("https://spark-class-social-network-api.hoff.tech/").done(function (data) {
    console.log(data);
});

Why don't we use https://www.google.com? Check out Cross-origin resource sharing: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

AJAX / XMLHttpRequest

AJAX stands for Asynchronous JavaScript and XML.

AJAX is the technique by which we use JavaScript to fetch data from other servers - exactly what we were just doing.

AJAX relies on the Browser API XMLHttpRequest to make HTTP requests.

While I hope you never ever have to build an XMLHttpRequest manually (it's obnoxiously complicated), it is good to know that the underlying technology exists - that's a question I've actually had in an interview.

MDN's intro on AJAX: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

MDN's official docs on XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Getting data from an API with jQuery's $.ajax()

Now, let's actually get the list of posts from the Social Network API! Let's look at the "Getting Started" section on https://spark-class-social-network-api.hoff.tech/#getting-started:

<!-- index.html -->

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    </head>
    <body>
        <script src="myscript.js"></script>
    </body>
</html>
// myscript.js

$.ajax({
    url: "https://spark-class-social-network-api.hoff.tech/api/posts",
    method: "GET"
}).done(function(data) {
    // the request has succeeded
    console.log(data);
}).fail(function(jqXHR, status, error) {
    // the request has failed
    console.log(error);
});

Hey look! The data that the API gives us back is already in the format of a JavaScript object or array. That's convenient!

$.ajax "callback" vs "promises"

You used to be able to handle AJAX responses like this (the "callbacks" way):

// myscript.js

$.ajax({
    url: "https://spark-class-social-network-api.hoff.tech/api/posts",
    method: "GET"
}, function(data) {
    console.log(data);
});

However, they've removed support for this in the latest jQuery version, and I don't recommend doing it this way. You'll likely see lots of examples on the internet doing it this way.

My recommendation is to handle AJAX responses like this (the "promises" way):

// myscript.js

$.ajax({
    url: "https://spark-class-social-network-api.hoff.tech/api/posts",
    method: "GET"
}).done(function(data) {
    // the request has succeeded
    console.log(data);
}).fail(function(jqXHR, status, error) {
    // the request has failed
    console.log(error);
});

That's all I've got for today!

What questions are there?

How to be a Web Developer

  1. Look stuff up on the internet
  2. Make stuff
  3. Repeat

Excelsior! 🚀