Bricktowntom is committed to exceeding your expectations by providing a positive, enjoyable experience while visiting my site. Thank you for considering Bricktowntom's Market Place. I appreciate the trust you have placed in me!!
Ajax/jQuery.getJSON Simple Example

Ajax/jQuery.getJSON Simple Example


Ajax/jQuery.getJSON Simple Example

In this article, we’ll investigate the importance of JSON and why we should use it in our applications. We’ll see that jQuery has got us covered with a very nice convenience function.

What is JSON?

JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is commonly used for transmitting data in web applications. In this article, we’ll look at loading JSON data using an HTTP GET request (we can also use other verbs, such as POST).

Why would we choose JSON over say XML? The key advantage of using JSON is efficiency. JSON is less verbose and cluttered, resulting in fewer bytes and a faster parse process. This allows us to process more messages sent as JSON than as XML. Moreover, JSON has a very efficient and natural object representation leading to formats such as BSON, where JSON-like objects are stored in a binary format.

Now, let’s see how jQuery can help us load JSON-encoded data from a remote source. For the impatient among you, there’s a demo towards the end of the article.

JSON jQuery Syntax

The $.getJSON() method is a handy helper for working with JSON directly if you don’t require much extra configuration. Essentially, it boils down to the more general $.ajax() helper, with the right options being used implicitly. The method signature is:

$.getJSON(url, data, success);

Besides the required URL parameter, we can pass in two optional parameters. One represents the data to send to the server; the other one represents a callback to trigger in case of a successful response.

So the three parameters correspond to:

  • the url parameter, which is a string containing the URL to which the request is sent
  • the optional data parameter, which is either an object or a string that’s sent to the server with the request
  • the optional success(data, textStatus, jqXHR) parameter, which is a callback function executed only if the request succeeds

In the simplest scenario, we only care about the returned object. In this case, a potential success callback would look like this:

function success(data) {
  // do something with data, which is an object
}

As mentioned, the same request can be triggered with the more verbose $.ajax() call. Here we would use:

$.ajax({
  dataType: 'json',
  url: url,
  data: data,
  success: success
});

Let’s see this in practice using a little demo.

A Sample Application

We’ll start a local server that serves a static JSON file. The object represented by this file will be fetched and processed by our JavaScript code. For the purposes of our demo, we’ll use Node.js to provide the server (although any server will do). This means we’ll need the following three things:

  • a working installation of Node.js
  • the node package manager (npm)
  • a global installation of the live-server package

The first two points are platform-dependent. To install Node, please head to the project’s download page and grab the relevant binaries for your system. Alternatively, you might like to consider using a version manager as described in “Installing Multiple Versions of Node.js Using nvm”.

npm comes bundled with Node, so there’s no need to install anything. However, if you need any help getting up and running, consult our tutorial “A Beginner’s Guide to npm — the Node Package Manager”.

The third point can be achieved by running the following from your terminal:

npm install -g live-server

If you find yourself needing a sudo prefix (-nix systems) or an elevated command prompt to perform this global installation, you should consider changing the location of global packages.

Once these requirements have been met, we can create the following three files in a new folder:

  • main.js, which is the JavaScript file to request the data
  • example.json, which is the example JSON file
  • index.html, which is the HTML page to call the JavaScript and display the data

From the command prompt we can simply invoke live-server within the new folder. This will open our demo in a new browser tab, running at http://localhost:8080.

The Sample JavaScript

The following code is the complete client-side logic. It waits for the DOMContentLoaded loaded event to fire, before grabbing a reference to two DOM elements — $showData, where we’ll display the parsed response, and $raw, where we’ll display the complete response.

We then attach an event handler to the click event of the element with the ID get-data. When this element is clicked, we attempt to load the JSON from the server using $.getJSON(), before processing the response and displaying it on the screen:

$(document).ready(() => {
  const $showData = $('#show-data');
  const $raw = $('pre');

  $('#get-data').on('click', (e) => {
    e.preventDefault();

    $showData.text('Loading the JSON file.');

    $.getJSON('example.json', (data) => {
      const markup = data.items
        .map(item => `<li>${item.key}: ${item.value}</li>`)
        .join('');

      const list = $('<ul />').html(markup);

      $showData.html(list);

      $raw.text(JSON.stringify(data, undefined, 2));
    });
  });
});

Besides converting parts of the object to an unordered list, the full object is also stringified and displayed on the screen. The unordered list is added to a <div> element with the ID show-data, the JSON string a <pre> tag, so that it is nicely formatted. Of course, for our example the data is fixed, but in general any kind of response is possible.

Note that we also set some text for the output <div>. If we insert some (artificial) delay for the JSON retrieval (for example, in your browser’s dev tools), we’ll see that this actually executes before any result of the $.getJSON request is displayed. The reason is simple: by default, $.getJSON is non-blocking — that is, async. Therefore, the callback will be executed at some (unknown) later point in time.

Distilling the source to obtain the crucial information yields the following block:

$('#get-data').on('click', () => {
  $.getJSON('example.json', (data) => {
    console.log(data);
  });
});

Here we only wire the link to trigger the start of the $.getJSON helper before printing the returned object in the debugging console.

Continue reading
Ajax/jQuery.getJSON Simple Example
on SitePoint.

Source: Site Point

 

Republished by Blog Post Promoter