Skip to content
Advertisement

Get API data form URL to display

I am trying to build a basic tool to display someones congress representative via zipcode.

The API that I am trying to use is offered for free via: https://whoismyrepresentative.com

The link to get the info via zipcode is: https://whoismyrepresentative.com/getall_mems.php?zip=31023

It can also be formatted for json like this: https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json

I have read a ton of articles on how to display this data but the trouble I am having is getting the data to show up at all.

How can I get the data to display on my page.

My first attempt was based off w3schools example. When the button is clicked is should display the result in the empty div but when I replace the URL, it does not display. When you visit the URL directly the data is there.

My JavaScript knowledge is fairly limited so I will go line by line and maybe I am just misunderstanding something.

$(document).ready(function(){ – Gets the document ready for some jquery

$("button").click(function(){ – Sets up click function on <button>

$.getJSON("https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json", function(results){ – I hope this is what gets the data from the API URL

$.each(results, function(i, field){ – I’m not sure what this does but I am thinking this displays the field for ‘results’

$("div").append(field + " "); – This will display the data in the empty <div>

Full index.php code

JavaScript

ATTEMPT II

OK I think I have a better understanding but am still confused about some stuff below is my updated code based on your sample with some notes.

JavaScript

ATTEMPT III

Updated with new comments and questions.

JavaScript

Advertisement

Answer

You are close.

Let me help by explaining first how to interpret the function calls.

$(document) is a jQuery selector that fetches the active HTMLDocument object.

On that object, we are then calling the method ready, which waits for the document to finish loading. It is an event listener that waits for the ‘onReady’ event of the document. Once that event is detected, we know that the document and all its components have been fully loaded.

At that time, we execute the anonymous function within the ready method call. There we find:

JavaScript

You are correct. The $("button") code fetches all objects that are loaded into the document having the “button” tag name. In this case, there is only one button. The method click is then called, which sets the event listener on the button object, and the event listener will be called each time the associated button is clicked.

The function that is called contains the following code:

JavaScript

Because of its location, this code is run each time the button is clicked. The $ symbol is a variable name that links to the loaded jQuery library. Within that library, we are calling the getJSON method, which will fetch JSON from a provided URL (your first argument), and then it will return it asyncronously to any function that you provide. In this case, you have provided an anonymous function:

JavaScript

The results will be your JSON object. As you expect.

So far, your understanding of the above was close enough to get you by. Your trouble really starts with understanding $.each().

Remember that $ is the jQuery library. each() is a function that is just like a for…each loop.

In this case, the call to $.each( results, function(i,field){...} ); does the following. It iterates over each item in the results object, and it then calls the function once for each item. The first argument in the function (i) is the index in the results array, and the second argument (field) is the actual item itself.

For example, lets assume I have the following code:

JavaScript

Within each call to the function(i, itemName){...} block, I will see the following:

  1. On the first call, i=0 and itemName="item1".
  2. On the second call, i=1 and itemName="item2".
  3. On the third call, i=2 and itemName="item3".
  4. There will be no forth call, because the loop is done.

So, $.each( array, function(){} ) will apply the function to each element of the array.

What this means is that the JSON data that you are interested in will be in the field variable of the function call, so when the function executes:

JavaScript

The code does the following:

  1. Pass the value “div” to the jQuery locator, which fetches all instances of items that are identified by “div” tags.
  2. Call the append method on the DIV element.
  3. Add the field value and a whitespace to the end of the element contents.

In order to understand what is happening, I would recommend using fewer anonymous functions and using console.log(...) and debugger statements to help inspect the code while it is running. When you can see in the console what is contained within each field variable, you can better understand the data that is being presented to you, and then you can play with formatting a little more clearly.

To assist you on your journey, I have refactored the code to be more clear by removing anonymous functions:

JavaScript
JavaScript

Side note, the method “getJSON” is a shortcut method, and it is not defined in all versions of jQuery. I had trouble getting this specific method to work in my browser, so it is better, always, to use the main method, which in this case is $.ajax().

Note to Other Users

The answer above remains the recommended action. The user Heck Raiser and I have begun exchanging emails to help further his understanding of the above code. He is updating his question to reflect his increased understanding based on the discussions we are having. This does not change the above answer.

One of the problems that Heck Raiser will face is that his browser is blocking the JSON response because of CORS. I have recommended to him that he make the JSON request from his server and that he direct his browser to call the server code instead. This will keep the domain name the same, which will not raise any flags for the browser and will allow the JSON response to be handled without CORS errors.

Heck Raiser has elected to use PHP for the backend implementation of this, but the language used is irrelevant for the technique. What is important is this: to get around CORS errors, you must call a page that exists on the same domain as the page that the jQuery is currently running from.

enter image description here

Advertisement