Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Last active January 31, 2017 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewman12/d0d0b7005b99e7bd89f99bdb91e34b9d to your computer and use it in GitHub Desktop.
Save jnewman12/d0d0b7005b99e7bd89f99bdb91e34b9d to your computer and use it in GitHub Desktop.
Ajax Lesson

AJAX with JS & JQuery

Objectives

  • Implement a jQuery AJAX client for a simple REST service
  • Reiterate the benefits of separation of concerns – API vs. Client

Preparation

  • Understand basics of JS
  • Understand what jQuery is and how to use it for DOM manipulation
  • Understand HTTP verbs & the concept of RESTful JSON APIs

What is AJAX? Introduction

AJAX (Asynchronous JavaScript and XML) is a method of building interactive applications for the Web that processes user requests immediately, without re-rendering a whole page.

Example: A weather forecasting site could display local conditions on one side of the page as soon as a user finishes typing in a zip code. The temperature could refresh every minute, without the user having to hit a refresh button.

In general the process looks like this – use JavaScript on the client side to hit an API (without reloading a page), then use the pure data you get back to manipulate the DOM somehow if you need to. This DOM manipulation can take the form of rendering a template or just changing a number on the page.

Advantages

  • Faster - This is the most obvious reason for using AJAX on your frontend: AJAX allows easier and quicker interaction between user and website as pages are not reloaded for content to be displayed. The server doesn't have to get data, render HTML, and then spit it out, it just has to get data and your already-loaded frontend does the rest.

  • Compact - With AJAX, several application features can be handled using a single web page. That means we modularize our app into smaller bits, and it becomes easier to work on.

  • Backend Separated from Frontend - Applications that use AJAX-heavy frontends mean developers don't have to work on both sides of the stack at the same time. Some developers can be dedicated to building an API that just serves data, and others can focus on consuming that data and building interfaces.

Disadvantages

  • The back and refresh button are rendered useless - Since things are loaded dynamically on a page, without that page reloading (or more importantly, without a URL being changed), clicking the back or refresh button doesn't work the way you're used to. That's actually a pretty big deal – UX designers are very familiar with the fact that users are accustomed to being able to hit back when they need to. Some advanced front-end frameworks have tried to solve this issue with clever workarounds, but that's not always the case and not always accurate.

  • Javascript can be disabled - While javascript is secure and has been heavily used by websites for a long period of time, a percentage of website surfers prefer to turn javascript functionality off on their browser, rendering the AJAX application totally useless. That's not always the best thing to design for, and more often than not, you'll find yourself assuming users have JS on, but it's important to know your whole site could be useless in some situations. Nowadays most websites use JavaScript, so it's very uncommon for users to disable it.

  • You have to consider the UX even more - While UX is crucial for any application, the fact that a page doesn't refresh means you have to be even more considerate of what a user is experiencing. If something in your JavaScript goes wrong, your AJAX breaks, and you don't have failsafes thoughtfully built in, your user might be clicking a button and seeing absolutely nothing happen. Most common users won't have their consoles open to notice any errors.

Why are we learning it?

As you're learning how to build APIs on the server side, you need to start learning how to consume your APIs on the client side.

While we're going to be tackling some advanced front-end frameworks in the next unit, you, as a junior full-stack developer, need to be able to do something awesome with the APIs you're learning to make. So we're going to tackle the basics and build on them even further later.

Setup - Codealong

While we're still learning the ins-and-outs of building APIs, let's use an already-made API for today that handy thing lives at https://agile-chamber-77499.herokuapp.com/artists – it's a simple dummy data service that'll let us do GETs & POSTs quickly. This API uses patch, not put, for updates.

While you're at it, in the starter-code folder, we've got a super basic index and a CSS file to get started. Nothing fancy.

Open up your index.html in a browser, and make sure to load up that console - we're going to be working with it quite a bit.

Now, we've set a few things up for you. We've got here a form with 2 inputs. We've also already included jQuery.


jQuery GET Requests

  • Get requests in Ajax, like most data we work with, is what you are generally going to be using the most
  • jQuery has a shorthand method for just submitting get requests
  • $.get looks like this: $.get(URL,callback);
  • This is what a basic jquery get request looks like
$.get("https://our.api.com/api", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});
  • this piece of code submits a get request at a certain endpoint and we tack on a function that loads the data onto our page

jQuery Post Requests

  • The $.post() method requests data from the server using an HTTP POST request.
  • The required URL parameter specifies the URL you wish to request.
  • The optional data parameter specifies some data to send along with the request.
  • The optional callback parameter is the name of a function to be executed if the request succeeds.
  • The following example uses the $.post() method to send some data along with the request:
$("button").click(function(){
    $.post("https://our.api.com/api",
    {
        name: "Donald Duck",
        city: "Duckburg"
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});
  • The first parameter of $.post() is the URL we wish to request.
  • Then we pass in some data to send along with the request (name and city).
  • The API endpoint reads the parameters, processes them, and returns a result.
  • The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

jQuery $.ajax Requests

  • We have seen two short-hand ways in which we deal with $.ajax requests, but jQuery has an even more versatile way for us to structure our requests
  • the $.ajax is considered the long-form way of approaching this, but is more versatile in what we can do to it
  • The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
  • All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
  • the syntax looks like this: $.ajax({name:value, name:value, ... })
$.ajax({
    url : "https://our.api.com/api",
    type: "GET", // or POST
    data: ourObject,
    success: function(data, textStatus, jqXHR) {
      console.log(data);
      doStuffOnSuccess(data);
    },
    error: function (jqXHR, textStatus, error) {
      console.log(jqXHR);
      console.log(textStatus);
      console.log(error);
    }
  });
  • this is basically the same functionality as $.get and $.post above, but allows us to have a little bit more diversity in how we approach our requests
  • In jQuery's documentation you can find all the chainable callback function possibilities – the three you'll probably use a lot are .done, .fail, and .always.
  • On our Ajax method, we can tack on 2 additional properties success and error
  • This is also very similar to how angular handles HTTP requests, and we will see that next section

Mini-Lab

Now, let's go over our mini-lab!


Conclusion

  • What's the main use case of AJAX? Why would anyone use it?
  • How do you do a GET request with jQuery?
  • How do you do a PUT, POST, or DELETE request in jQuery?

Extra Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment