DEV Community

Cover image for Software Dev Weekly Update #2: AJAX & APIs
Ethan Goddard
Ethan Goddard

Posted on • Edited on

Software Dev Weekly Update #2: AJAX & APIs

We covered AJAX (AJAJ), APIs, and Prototypes. Below is a simple/practical example of utilizing the TVMAZE API to get TV show information based on user input and displaying images of the first 10 results.

We used the Postman tool to test using different headers and get an easy visual of the data sent back.

I also spent time on a programming learning app called SoloLearn. The JavaScript course presents you with quick challenges and I focused on the Conditionals and Loops section. It's been a great way to practice concepts and helps the info sink in!

TV Show API Demo

JavaScript


//This function makes the API data request for whatever search we input and also clears the images when a new search is performed
const form = document.querySelector('#searchForm');
const displayArea = document.getElementById('requestImages');
form.addEventListener('submit', async function(event){
    event.preventDefault();
    displayArea.innerHTML = '';
    const searchTerm =  form.elements.query.value;
    const config = {params:{q:searchTerm}}
    const response = await axios.get('https://api.tvmaze.com/search/shows', config);
    makeImages(response.data);
    form.elements.query.value = '';
})

//This function filters out just the medium image URLs and appends them to the page (and only if a medium image is availale) and clears the search box after submission
const makeImages = function(shows){
    for(let result of shows){
        if(result.show.image){
            const tvShowImage = document.createElement('IMG');
            tvShowImage.src = result.show.image.medium;
            displayArea.append(tvShowImage);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>TV Show Search App</h1>
    <form id="searchForm">
        <input type="text" placeholder="TV Show Title" name="query">
        <button>Search</button>
        <div id="requestImages"></div>
    </form>
    <script src="TV_Show_Search_App.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the read!

Feel free to follow me on GitHub, LinkedIn and DEV for more!

Top comments (0)