Skip to content

Instantly share code, notes, and snippets.

@tmcw
Last active April 19, 2021 21:08

Revisions

  1. tmcw revised this gist Feb 6, 2013. 1 changed file with 10 additions and 5 deletions.
    15 changes: 10 additions & 5 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,9 @@

    I will assume that you are familiar with Javascript and HTML - read up on [jsforcats.com](http://jsforcats.com/) if you need Javascript chops, and [Learn HTML](https://developer.mozilla.org/en-US/learn/html) for HTML.

    You've heard of AJAX, and it's a bit confusing. Let's clear things up. Like Javascript for Cats, it's best to use Google Chrome for this, and to use your [web developer extensions](http://macwright.org/enable-web-developer-extensions/).
    AJAX is a feature of Javascript and your browser that downloads new data after you initially request a page: so you live-update content and pull in new bits of content a user requests. AJAX is how the [Pinterest](http://pinterest.com/) home page keeps loading content when you scroll, and it's how Gmail can ring in new emails without requiring you to click 'refresh' all the time.

    Let's clear things up. Like Javascript for Cats, it's best to use Google Chrome for this, and to use your [web developer extensions](http://macwright.org/enable-web-developer-extensions/).

    ## Requests

    @@ -34,11 +36,13 @@ A faster way to do this would be to request _something new_, after the page has

    ## Meet XMLHttpRequest

    The fathers of the internet gave AJAX a rather awkward name - XMLHttpRequest. Luckily, smart young nerds have made it more accessible through programming libraries like [jQuery](http://jquery.com/), so you'll be able to use it just like `$.ajax` - which is much easier to remember. But let's start off with the basics, and the underlying code.
    The fathers of the internet gave AJAX a rather awkward name - XMLHttpRequest.

    The `XML` in the name is irrelevant most of the time - you can use it to download XML, but most of time time you'll be downloading other types of files, like text files.

    I'll assume you know basic Javascript, but explain the tricky part that this will introduce.
    `HTTP` is _how_ you request files - it's the system through which you download web pages and images normally, and XMLHttpRequest just uses it more, to download new things.

    Meet `XMLHttpRequest`. The XML in the name is irrelevant for most of the way you'll use it - you can request XML documents with it, but also a lot of other stuff. HTTP is true: it's the system through which you download web pages, javascript, images, and so on.
    And, of course, it's all about `Request`ing content.

    `XMLHttpRequest` is a Javascript class, and it's one of the ones provided by your browser: it's built-in if you're writing Javascript in a webpage. You already have it.

    @@ -199,4 +203,5 @@ The `$.ajax` function additionally accepts a [whole lot of other options](http:/

    ### Footnotes

    1. There are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), but it's usually something you have to live with.
    1. There are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), but it's usually something you have to live with.
    2.
  2. tmcw revised this gist Feb 5, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@ You've heard of AJAX, and it's a bit confusing. Let's clear things up. Like Java

    ## Requests

    Most web pages have more than one part: the initial page you download is `index.html`, but there are other parts: images, CSS styles, Javascript files. An `index.html` might look like:
    When you go to a webpage, your browser downloads parts of it. Most web pages have more than one part: the initial page you download is `index.html`, but there are other parts: images, CSS styles, Javascript files, and more. An `index.html` might look like:

    ```html
    <html>
    @@ -22,7 +22,7 @@ Most web pages have more than one part: the initial page you download is `index.
    </html>
    ```

    When your browser sees this page, it notices that it requires `style.css`, `jquery.js`, and `site.js`, and it goes out and downloads them from the same server before displaying the page. If you open up the 'Network Resources' tab of your Google Chrome and load a page, you can see this requests going out and coming in.
    Your browser sees this page, notices that it'll need `style.css`, `jquery.js`, and `site.js`, and it goes out and downloads them from the same server before displaying the page. If you open up the 'Network Resources' tab of your Google Chrome and load a page, you can see this requests going out and coming in.

    And so browsers have the ability to _request_ things like CSS, Javascript, images, and HTML. But they do these requests the first time you load a page.

  3. tmcw revised this gist Feb 5, 2013. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -193,6 +193,10 @@ $.ajax('weather.txt', {

    The `$.ajax` function additionally accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).

    ### References

    * Want to know everything about `XMLHttpRequest`? [Read XMLHttpRequest on Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest).

    ### Footnotes

    1. There are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), but it's usually something you have to live with.
  4. tmcw revised this gist Feb 4, 2013. 1 changed file with 8 additions and 8 deletions.
    16 changes: 8 additions & 8 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    ## AJAX For Cats

    I'll assume that you're familiar with Javascript and HTML - read up on [jsforcats.com](http://jsforcats.com/) if you need Javascript chops, and [Learn HTML](https://developer.mozilla.org/en-US/learn/html) for HTML.
    I will assume that you are familiar with Javascript and HTML - read up on [jsforcats.com](http://jsforcats.com/) if you need Javascript chops, and [Learn HTML](https://developer.mozilla.org/en-US/learn/html) for HTML.

    You've heard of AJAX, and it's a bit confusing. Let's clear things up. Like Javascript for Cats, it's best to use Google Chrome for this, and to use your [web developer extensions](http://macwright.org/enable-web-developer-extensions/).

    @@ -28,9 +28,9 @@ And so browsers have the ability to _request_ things like CSS, Javascript, image

    What if you want content after you request a page? If you have want to have a temperature ticker, and so you have a section of your page like `<div id='temperature'>90</div>`, but you want it to update quickly?

    One option would be to tell users to refresh the page, or to have the page auto-refresh. It's doable, but that way you'll have to re-request everything every couple of minutes, or even seconds.
    One option would be to tell users to refresh the page, or to have the page auto-refresh. It's doable, but that way you will have to re-request everything every couple of minutes, or even seconds.

    A better way to do this would be to request _something new_, after the page has been initially loaded. This is what AJAX lets us do.
    A faster way to do this would be to request _something new_, after the page has been initially loaded. This is what AJAX lets us do.

    ## Meet XMLHttpRequest

    @@ -54,7 +54,7 @@ Let's repeat: _AJAX is a way to request new files after your web page has finish

    ## Your First Event

    Let's take the next part slow: it's a tricky part of Javascript but a really important one to understand.
    Let's take the next part slow: it is a tricky part of Javascript but an important one to understand.

    ```js
    request.onload = function() {
    @@ -106,11 +106,11 @@ request.send();

    ## Nitpicky Details

    See how we're requesting `weather.txt`? While you can get a lot of stuff with AJAX, you can't get everything. Exceptions include:
    See how we're requesting `weather.txt`? Although you can get a lot of stuff with AJAX, you can't get everything. Exceptions include:

    Stuff on different domains than the one you're on. For instance, if you have a site at `www.tomscats.com`, you can't do an AJAX request grabbing the cat listing at `www.alexscats.com`. The technical reason for this is the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy).<sup>[1]</sup>

    AJAX can request text-based stuff: while you can technically do an AJAX request for an image, movie, or another non-text-based file, it's not likely to be very useful or fast.
    AJAX can request text-based stuff: although you can technically do an AJAX request for an image, movie, or another non-text-based file, it is not likely to be very useful or fast.

    ## All Together Now

    @@ -174,7 +174,7 @@ Then you only get alerted of the sky color once `skycolor.txt` is downloaded - s

    ## Meet jQuery

    Initially, web browsers didn't support AJAX very well - they lacked some parts of it or had
    Initially, web browsers didn't support AJAX well - they lacked some parts of it or had
    kind-of-the-same-but-not-the-same ripoffs of the technique. Mostly these are older browsers
    now - [Internet Explorer 5-6](http://en.wikipedia.org/wiki/XMLHttpRequest#Support_in_Internet_Explorer_versions_5.2C_5.5.2C_and_6), but it's good to be wary.

    @@ -191,7 +191,7 @@ $.ajax('weather.txt', {
    })
    ```

    The `$.ajax` function also accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).
    The `$.ajax` function additionally accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).

    ### Footnotes

  5. tmcw revised this gist Feb 4, 2013. 1 changed file with 12 additions and 3 deletions.
    15 changes: 12 additions & 3 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -50,6 +50,8 @@ var request = new XMLHttpRequest();

    So, `XMLHttpRequest` is the class - it's the type of thing - and you've created a new one that you've named `request`. But you haven't told it what you want, or what it should do once you've got it.

    Let's repeat: _AJAX is a way to request new files after your web page has finished loading_.

    ## Your First Event

    Let's take the next part slow: it's a tricky part of Javascript but a really important one to understand.
    @@ -106,7 +108,7 @@ request.send();

    See how we're requesting `weather.txt`? While you can get a lot of stuff with AJAX, you can't get everything. Exceptions include:

    Stuff on different domains than the one you're on. For instance, if you have a site at `www.tomscats.com`, you can't do an AJAX request grabbing the cat listing at `www.alexscats.com`. The technical reason for this is the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) and while there are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), it's usually something you have to live with.
    Stuff on different domains than the one you're on. For instance, if you have a site at `www.tomscats.com`, you can't do an AJAX request grabbing the cat listing at `www.alexscats.com`. The technical reason for this is the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy).<sup>[1]</sup>

    AJAX can request text-based stuff: while you can technically do an AJAX request for an image, movie, or another non-text-based file, it's not likely to be very useful or fast.

    @@ -173,7 +175,10 @@ Then you only get alerted of the sky color once `skycolor.txt` is downloaded - s
    ## Meet jQuery

    Initially, web browsers didn't support AJAX very well - they lacked some parts of it or had
    kind-of-the-same-but-not-the-same ripoffs of the technique. In order to avoid thinking about
    kind-of-the-same-but-not-the-same ripoffs of the technique. Mostly these are older browsers
    now - [Internet Explorer 5-6](http://en.wikipedia.org/wiki/XMLHttpRequest#Support_in_Internet_Explorer_versions_5.2C_5.5.2C_and_6), but it's good to be wary.

    In order to avoid thinking about
    those nitpicky differences, many people use [jQuery](http://jquery.com/).

    For instance, our weather-checking example from earlier would look like
    @@ -186,4 +191,8 @@ $.ajax('weather.txt', {
    })
    ```

    The `$.ajax` function also accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).
    The `$.ajax` function also accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).

    ### Footnotes

    1. There are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), but it's usually something you have to live with.
  6. tmcw revised this gist Feb 4, 2013. 1 changed file with 19 additions and 1 deletion.
    20 changes: 19 additions & 1 deletion ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -168,4 +168,22 @@ request.onload = function() {
    request.send();
    ```

    Then you only get alerted of the sky color once `skycolor.txt` is downloaded - so it'll be `red`.
    Then you only get alerted of the sky color once `skycolor.txt` is downloaded - so it'll be `red`.

    ## Meet jQuery

    Initially, web browsers didn't support AJAX very well - they lacked some parts of it or had
    kind-of-the-same-but-not-the-same ripoffs of the technique. In order to avoid thinking about
    those nitpicky differences, many people use [jQuery](http://jquery.com/).

    For instance, our weather-checking example from earlier would look like

    ```js
    $.ajax('weather.txt', {
    success: function(resp) {
    alert(resp.response);
    }
    })
    ```

    The `$.ajax` function also accepts a [whole lot of other options](http://api.jquery.com/jQuery.ajax/).
  7. tmcw revised this gist Feb 4, 2013. No changes.
  8. tmcw created this gist Feb 4, 2013.
    171 changes: 171 additions & 0 deletions ajax_for_cats.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,171 @@
    ## AJAX For Cats

    I'll assume that you're familiar with Javascript and HTML - read up on [jsforcats.com](http://jsforcats.com/) if you need Javascript chops, and [Learn HTML](https://developer.mozilla.org/en-US/learn/html) for HTML.

    You've heard of AJAX, and it's a bit confusing. Let's clear things up. Like Javascript for Cats, it's best to use Google Chrome for this, and to use your [web developer extensions](http://macwright.org/enable-web-developer-extensions/).

    ## Requests

    Most web pages have more than one part: the initial page you download is `index.html`, but there are other parts: images, CSS styles, Javascript files. An `index.html` might look like:

    ```html
    <html>
    <head>
    <title>My Homepage></title>
    <link href='style.css' type='text/css' rel='stylesheet' />
    <script src='jquery.js'></script>
    <script src='site.js'></script>
    </head>
    <body>
    <p>Hello, world!</p>
    </body>
    </html>
    ```

    When your browser sees this page, it notices that it requires `style.css`, `jquery.js`, and `site.js`, and it goes out and downloads them from the same server before displaying the page. If you open up the 'Network Resources' tab of your Google Chrome and load a page, you can see this requests going out and coming in.

    And so browsers have the ability to _request_ things like CSS, Javascript, images, and HTML. But they do these requests the first time you load a page.

    What if you want content after you request a page? If you have want to have a temperature ticker, and so you have a section of your page like `<div id='temperature'>90</div>`, but you want it to update quickly?

    One option would be to tell users to refresh the page, or to have the page auto-refresh. It's doable, but that way you'll have to re-request everything every couple of minutes, or even seconds.

    A better way to do this would be to request _something new_, after the page has been initially loaded. This is what AJAX lets us do.

    ## Meet XMLHttpRequest

    The fathers of the internet gave AJAX a rather awkward name - XMLHttpRequest. Luckily, smart young nerds have made it more accessible through programming libraries like [jQuery](http://jquery.com/), so you'll be able to use it just like `$.ajax` - which is much easier to remember. But let's start off with the basics, and the underlying code.

    I'll assume you know basic Javascript, but explain the tricky part that this will introduce.

    Meet `XMLHttpRequest`. The XML in the name is irrelevant for most of the way you'll use it - you can request XML documents with it, but also a lot of other stuff. HTTP is true: it's the system through which you download web pages, javascript, images, and so on.

    `XMLHttpRequest` is a Javascript class, and it's one of the ones provided by your browser: it's built-in if you're writing Javascript in a webpage. You already have it.

    You can create a new request like so:

    ```js
    var request = new XMLHttpRequest();
    ```

    So, `XMLHttpRequest` is the class - it's the type of thing - and you've created a new one that you've named `request`. But you haven't told it what you want, or what it should do once you've got it.

    ## Your First Event

    Let's take the next part slow: it's a tricky part of Javascript but a really important one to understand.

    ```js
    request.onload = function() {
    alert(request.reponse);
    };
    ```

    This needs some explanation, right? Okay.

    So, if you're coming from Python or some other language, or if you just have a searching mind, you might expect this code to read a bit more like

    ```js
    var response = request.load('http://google.com/');
    ```

    Right? Yes.

    Here it goes: what you're doing in Javascript is using **events**. This can be harder to understand than just 'doing it', but it's an important part of Javascript, and a big part of why it works quite well.

    When you set `request.onload`, you're setting a function that runs _when the response is received_. It might take two seconds to get that response. It might just never come. So it's good that the rest of your code isn't pausing to wait for its arrival: there's other important work to be done.

    An experienced or astute reader might notice that this code looks quite similar to click events:

    ```js
    buttonElement.onclick = function() { alert('hi!'); };
    ```

    It's similar, and for the same reason: we don't know when a user will click or whether they never will, so let's not sit around waiting.

    Got the advantage of events? We'll return to them later.

    ## Making the Request

    Now that you've told your script what you'll do once you get a response, let's make the request:

    ```js
    request.open('GET', 'weather.txt', true);
    ```

    `GET` is the name of the HTTP Method you'll be using. `GET` is used for… well, getting things. There are others, like `POST`, which we submit forms with, and a few others that are less popular.

    `weather.txt` is the name of the file you want. The third argument is `true`: don't worry about that one.

    So now we know what we want and what we'll do once we get it. Let's press go.

    ```js
    request.send();
    ```

    ## Nitpicky Details

    See how we're requesting `weather.txt`? While you can get a lot of stuff with AJAX, you can't get everything. Exceptions include:

    Stuff on different domains than the one you're on. For instance, if you have a site at `www.tomscats.com`, you can't do an AJAX request grabbing the cat listing at `www.alexscats.com`. The technical reason for this is the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) and while there are some new ways around it like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), it's usually something you have to live with.

    AJAX can request text-based stuff: while you can technically do an AJAX request for an image, movie, or another non-text-based file, it's not likely to be very useful or fast.

    ## All Together Now

    So, from start to finish, making a request will be like:

    ```js
    var request = new XMLHttpRequest();

    request.open("GET", 'weather.txt', true);

    request.onload = function() {
    alert(request.response);
    };

    request.send();
    ```

    Let's return to that bit about events!

    So, the tricky thing about events is that they run _out of order_.

    Let's say that you have a button called `buttonElem` in Javascript.

    ```js
    var catMood = 'happy';
    buttonElem.onclick = function() {
    catMood = 'cranky';
    };
    alert(catMood);
    ```

    What will be alerted? If you guessed `happy`, you're right: your cat won't get `cranky` until someone clicks the button. So, the easy predictability of code running top-to-bottom is a bit lost. Such is life!

    So, remember: the same is true of AJAX.

    ```js
    var request = new XMLHttpRequest();
    var sky = 'blue';
    request.open("GET", 'skycolor.txt', true);
    request.onload = function() {
    stockStatus = 'red';
    };
    request.send();
    alert(sky);
    ```

    The sky will still be `blue` when you get alerted, since the file, `skycolor.txt` is still being loaded - you're still waiting for it. If instead you write the code

    ```js
    var request = new XMLHttpRequest();
    var sky = 'blue';
    request.open("GET", 'skycolor.txt', true);
    request.onload = function() {
    stockStatus = 'red';
    alert(sky);
    };
    request.send();
    ```

    Then you only get alerted of the sky color once `skycolor.txt` is downloaded - so it'll be `red`.