Harnessing the Power of Pokémon: Dynamic Selection and API Integration with HTML, PHP, and JavaScript

Welcome, Pokémon enthusiasts! In this tutorial, we’ll embark on an exciting coding adventure where HTML, PHP, and JavaScript come together to create a dynamic Pokémon Selector. What sets this tutorial apart? We’re delving into the world of PHP, which seamlessly interacts with the Pokémon API to fetch and display detailed information about your favorite Pokémon. Let’s dive in and explore the magic of web development and API integration as we bring your Pokémon selection to life! Get ready to catch ’em all in the virtual realm!

See also with only JavaScript: JSON and Fetch in JavaScript: A Practical Guide with Pokémon API Examples

Choose Your Pokémon:

Define Pokémon API URL

$pokemonListUrl = 'https://pokeapi.co/api/v2/pokemon/';

This line sets the URL of the Pokémon API endpoint that provides a list of Pokémon.

Fetch Pokémon List

$response = file_get_contents($pokemonListUrl);

The file_get_contents function is used to retrieve the content of the specified URL ($pokemonListUrl). In this case, it fetches the list of Pokémon in JSON format.

Decode JSON Response

$data = json_decode($response, true);

The json_decode function is used to decode the JSON response into a PHP associative array. The true parameter is passed to ensure that the JSON is decoded into an associative array rather than an object.

Generate HTML Options Dynamically:

foreach ($data['results'] as $pokemon) {
    $pokemonName = ucfirst($pokemon['name']);
    echo "";
}

This loop iterates through the array of Pokémon obtained from the API response ($data[‘results’]). For each Pokémon, it extracts the name, capitalizes the first letter using ucfirst, and dynamically generates an HTML

The resulting HTML might look like this:

<option value='https://pokeapi.co/api/v2/pokemon/1'>Bulbasaur</option>
<option value='https://pokeapi.co/api/v2/pokemon/2'>Ivysaur</option>
<!-- ... and so on for each Pokémon in the list -->

Full Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokémon Selector</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #pokemonInfo {
            max-width: 600px;
            margin: 20px auto;
        }
        img {
            max-width: 100%;
            height: auto;
        }
        h2 {
            color: #f00;
        }
        h3 {
            color: #00f;
        }
    </style>
</head>
<body>
    <h2>Select a Pokémon:</h2>
    <select id="pokemonSelector">
        <?php
        // PHP code to fetch Pokémon list and generate options dynamically
        $pokemonListUrl = 'https://pokeapi.co/api/v2/pokemon/';
        $response = file_get_contents($pokemonListUrl);
        $data = json_decode($response, true);
        foreach ($data['results'] as $pokemon) {
            $pokemonName = ucfirst($pokemon['name']);
            echo "<option value='{$pokemon['url']}'>$pokemonName</option>";
        }
        ?>
    </select>
    <div id="pokemonInfo">
        <!-- Pokémon details will be displayed here -->
    </div>
    <script>
        // Function to fetch and display details of the selected Pokémon
        async function fetchAndDisplayPokemonDetails() {
            const pokemonSelect = document.getElementById('pokemonSelector');
            const selectedPokemonUrl = pokemonSelect.value;
            try {
                const response = await fetch(selectedPokemonUrl);
                const pokemonDetails = await response.json();
                // Displays Pokémon details
                const pokemonInfoContainer = document.getElementById('pokemonInfo');
                pokemonInfoContainer.innerHTML = buildPokemonInfoHTML(pokemonDetails);
            } catch (error) {
                console.error('Error during the request:', error);
            }
        }
        // Function to build the HTML for Pokémon details
        function buildPokemonInfoHTML(data) {
            // Pokémon Name and ID
            const pokemonTitle = `<h2>${data.name.charAt(0).toUpperCase() + data.name.slice(1)} (ID: ${data.id})</h2>`;
            // Pokémon Image
            const pokemonImage = `<img src="${data.sprites.front_default}" alt="${data.name}">`;
            // Pokémon Types
            const types = data.types.map(type => type.type.name).join(', ');
            const pokemonTypes = `<h3>Type(s): ${types}</h3>`;
            // Pokémon Abilities
            const abilities = data.abilities.map(ability => ability.ability.name).join(', ');
            const pokemonAbilities = `<h3>Abilities: ${abilities}</h3>`;
            // Pokémon Stats
            const stats = data.stats.map(stat => `<p><strong>${stat.stat.name}:</strong> ${stat.base_stat}</p>`).join('');
            // Pokémon Weight
            const weight = `<p><strong>Weight:</strong> ${data.weight / 10} kg</p>`; // Converting from hectograms to kilograms
            // Building the final HTML
            const finalHTML = pokemonTitle + pokemonImage + pokemonTypes + pokemonAbilities + stats + weight;
            return finalHTML;
        }
        // Adds an event listener to load Pokémon details upon selection
        const pokemonSelect = document.getElementById('pokemonSelector');
        pokemonSelect.addEventListener('change', fetchAndDisplayPokemonDetails);
    </script>
</body>
</html>

Conclusion

Congratulations on successfully creating your dynamic Pokémon Selector! By combining HTML, PHP, and JavaScript, we’ve crafted a web page that not only allows users to choose their favorite Pokémon but also dynamically fetches and displays comprehensive details about each selection. The inclusion of PHP’s seamless interaction with the Pokémon API adds an extra layer of sophistication to our project. As you continue your coding journey, feel free to explore additional features and enhancements to make this Pokémon Selector truly your own. Happy coding, and may your web development adventures continue to be as exciting as a Pokémon battle!