Ajax + jQuery: An Introduction

JavaScript, Tutorial

Since Twitch released their ‘Twitch Extensions’ SDK, I’ve been having a lot of fun playing around with different things I can integrate into Twitch’s panels. I’ve build a WordPress Panel and I’m working on Tumblr and Instagram Panels (which require a lot more API work).  But the crux of everything I’ve been working on relies on getting data from source to destination in a way that makes sense to everyone. At one point, RSS feeds were the de-facto standard. Personally, I think there’s a better solution – one that uses a more pure form of data in transmission: Ajax.

Ajax, or (Asynchronous JavaScript and XML), uses JavaScript to pull a data-based content feed and display it somewhere in a content space.  I prefer using jQuery’s $.ajax function with a JSON feed, but there are numerous combinations of ajax and feeds you can use.  Today, we’re going to write a very simple “feed fetching” application that will allow us to not only fetch the feed, but to re-fetch it on demand.

See a working JSFiddle here: https://jsfiddle.net/45qsp39y/

HTML Markup

First off, we’re going to generate some basic HTML. We’re not going to re-invent the wheel here. We need two items: a container for the content we’re going to pull, and a mechanism for fetching more. A div and button will suffice:

<html>
  <head>
    ...
  </head>
  <body>
    <div id="feed"></div>
    <button class="button">Random Chuck Norris Joke</button>
  </body>
</html>

Notice how the #feed doesn’t have any additional fields; it’s just an empty container. We’re going to call some basic markup to fill that as we bring the feed in.

The jQuery / JavaScript

First off, we need to ensure that we’ve brought in the jQuery library:

<html>
  <head>
   <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <script type="text/javascript">
    ...
   </script>
  </head>
  <body>
    <div id="feed"></div>
    <button class="button">Random Chuck Norris Joke</button>
  </body>
</html>

We’re also going to include a script tag. Normally, you could include this in a script file to clear up the markup, but for a small example it’s fine to leave it inline so we can show our work.

Now, the fun part: including the $.ajax command that jQuery uses to fetch our feed.

function fetchFeed() {
  $.ajax({
    url: 'https://api.icndb.com/jokes/random',
    dataType: 'json',
    type: 'GET',
    success: function(data) {
      var output = '<p>' + data.value.joke + '</p>';
      $('#feed').html(output);
    },
    error: function(jqXHR, exception) {
      if (jqXHR.status === 0) {
        var output = '<p>Unable to access WordPress Posts. Please check your URL and try again!</p>';
     } else if (jqXHR.status == 404) {
       var output = '<p>The requested page not found. [404]</p>';
     } else if (jqXHR.status == 500) {
       var output = '<p>Internal Server Error [500].</p>';
     } else if (exception === 'parsererror') {
       var output = '<p>Requested JSON parse failed.</p>';
     } else if (exception === 'timeout') {
       var output = '<p>Time out error.</p>';
     } else if (exception === 'abort') {
       var output = '<p>Ajax request aborted.</p>';
     } else {
       var output = '<p>Uncaught Error.\n' + jqXHR.responseText + '</p>';
     }
       $('#feed').html(output);
     }
  });
}

$('button.button').click(function() {
 fetchFeed();
});

fetchFeed();

There’s a lot going on here. Let’s break it down:

  • Between lines 1 and  29 are the fetchFeed() function. This wraps all of the scripting we need to run into a function that we can call 1) automatically on page load and 2) on an action we will define later.
  • Line 2 starts the $.ajax function: a helper function included in jQuery that makes it easier to write AJAX calls.
  • Line 3 is our feed url – in this case, a random “Chuck Norris” joke. Because why not.
  • We’re telling our application what KIND of data to pull in Line 4. In this case, it’s JSON. If it were another format, we could define that here and jQuery would appropriately format said data.
  • Line 5 is how we’re approaching the data. We’re “GET”ing this data, which means we’re fetching data from another source. If we had the appropriate permissions we could also “POST” or “PUT” data onto an external server – good if we’re using a 3rd party access tool for an application. Usually we’d need some sort of API Key to do that. Since the Chuck Norris Joke website’s API is public, we don’t need that to just read the posts.
  • Lines 6-9 defines what we do on a “success” response. In this case, we’re setting an ‘output’ variable, and defining it as a bit of HTML. Inside of the HTML we’re pulling part of our “fetched feed” (data.value.joke). This varies based on the feed we’re working with, but it will always come back as data. Finally, we’re setting the HTML of the #feed container as our generated output.
  • Lines 10-27 are “error handlers”. Based on what response we get back on a failed fetch, i can display an error message. In this case, I’m displaying it in the feed container itself, but I could also echo this as a console.log if I were debugging.
  • Lines 31-33 are setting up a click event on the button we added. When that button is clicked, the fetchFeed() function is called immediately.
  • Line 35, once all of the other functions are done, will fire the fetchFeed() function on the initial page load.

Looking back at the JSFiddle you can see the script in action. On the initial page load, it’ll pull one random joke from the API. Pushing the button will load in a new joke and replace the HTML in the container with a new joke.

AJAX provides a fantastic, easy way to manage data without having to refresh a page. You can seamlessly reload data as it’s added, or provide an easy way to add content to a page without disturbing other elements on the page.