Using JQuery and AJAX to Display API Data on a Web Page

My last post demonstrated how JavaScript and JQuery can be used to make a API call and embed the response into a Document Object Model (DOM) instance. In that post’s example, the API was called, the data was retrieved and loaded into the DOM, but nothing was displayed on the web page.

In this post, I show how to access the API response data and present it on the web page. This is the next step in illustrating how the API Science API can be utilized to develop custom consoles and other applications that address your particular needs.

The HTML

Here’s the HTML file:

It consists of four components:

  • a heading titled “Response Data”
  • a <div> element (which identifies a division or section within an HTML document)
  • a <script> element that integrates JQuery
  • a <script> element that integrates our custom JavaScript code

The <div> element provides an interface through which our custom JavaScript code can modify the web page that is ultimately displayed to the user. The HTML identifies this particular <div> as being the “monitor_data” <div> element. Our custom JavaScript code can interact with this HTML <div> element, and alter its content prior to the presentation of the web page.

Here’s display_monitor_1572022.js:

$.ajax({
  url: "https://api.apiscience.com/v1/monitors/1572022",
  headers: {
    "Authorization" : "Bearer NN_6xxxxx"
  }
}).done(function(data) {
  $('#monitor_data').append(JSON.stringify(data))
});

The “Authorization” data would be your own API Science API key.

This JavaScript calls the API Science API to access the information form the user’s monitor ID 1572022. The .done(function(data)) phrase tells the HTML page to turn the JSON response into a string (stringify) and append the result into the monitor_data div element.

Here is an example result returned by this web page and its JavaScript files:

This illustrates that JQuery JavaScript can be utilized on a web page to query the API Science API, retrieve data, then display the data on a web page that is presented to a user.

The presentation of the data in this example is confusing, as it’s the raw JSON. In upcoming posts, I’ll illustrate code that deciphers the raw JSON and creates a web page that presents the data in a more understandable format.

–Kevin Farnham