Welcome back to another week of learning to code. This week we will dig a little more into some JQuery methods and begin working directly with an API. Until now, we have used the Yahoo Query Language too simplify the task of interacting with the Google API. Today we will begin interacting with the Alpha Vantage API, which offers real-time and historical stock quote information. This API has a very low barrier to entry, which makes it ideal for a learning environment. Today we will build a simple app that will allow a user to query the API for information on a particular stock. So, let’s get started.
Now, let’s start looking at our searchStock() function. We begin by referencing the table named output and the div tag named message. As before, we want to clear out the innerHTML in case of the user resubmitting the form. We also want to reference the stockSymbol that the user has typed in to the search box. Now, we begin looking at some more JQuery functionality. Remember, the dollar sign is the same as typing ‘JQuery’. So, $.getJSON could also be typed as JQuery.getJSON.
The getJSON() method is a shorthand way of calling the same Ajax method that we used last week. In this example, our first argument is the URL, which is a concatenation of our function call to the API, the symbol from our user, and our API key. The second argument is the success function that will be called on the data returned from the URL. We then create an empty array that will hold our HTML that we will eventually append to the output table. Our first element of this array will be the header for our table, which will include the stock symbol that our user has typed in. Here, we are again using template literals. Now, we want to show all the stock info to our user as rows in the table. So, we use the .each() JQuery method to iterate over the data and create cells for each key value pair in our JSON. Lastly, we want to present the user with an error message if no data is returned (i.e. the user typed in a bad stock symbol) and append our header and rows to the output table.
Throughout this short tutorial you have learned a little more JQuery functionality and how it can be used to simplify an HTTP request. Next week will add some more functionality to this little app to make it more responsive. Stay tuned. If you have any questions, please use the comment section below. Remember to share this post on your favorite social media platform. Thanks for stopping by, and I will see you all again next week.