Dynamic dropdown

 To achieve a dynamic dropdown menu that fetches rewards based on the selected user ID without a page reload, you'll need to use JavaScript and AJAX to interact with your PHP backend. Here's a step-by-step guide:


1. **HTML Form**: Create an HTML form with an input field for the user ID and an empty dropdown menu.


```html

<!DOCTYPE html>

<html>

<head>

    <title>Fetch User Reward</title>

</head>

<body>

    <form>

        <label for="user_id">Enter User ID:</label>

        <input type="text" name="user_id" id="user_id">

    </form>


    <select id="rewardDropdown">

        <option value="">Select User Reward</option>

    </select>


    <script src="script.js"></script>

</body>

</html>

```


2. **JavaScript (script.js)**: Create a JavaScript file to handle the user interaction.


```javascript

document.addEventListener("DOMContentLoaded", function () {

    const userIdInput = document.getElementById("user_id");

    const rewardDropdown = document.getElementById("rewardDropdown");


    userIdInput.addEventListener("input", function () {

        // Fetch rewards when user input changes

        const userId = userIdInput.value;

        if (userId) {

            fetchRewards(userId);

        }

    });


    function fetchRewards(userId) {

        // Send an AJAX request to the PHP script

        const xhr = new XMLHttpRequest();

        xhr.open("GET", `fetch_rewards.php?user_id=${userId}`, true);

        xhr.onreadystatechange = function () {

            if (xhr.readyState === 4 && xhr.status === 200) {

                const rewards = JSON.parse(xhr.responseText);

                populateDropdown(rewards);

            }

        };

        xhr.send();

    }


    function populateDropdown(rewards) {

        // Populate the dropdown with rewards

        rewardDropdown.innerHTML = "<option value=''>Select User Reward</option>";

        for (const reward of rewards) {

            rewardDropdown.innerHTML += `<option value="${reward}">${reward}</option>`;

        }

    }

});

```


3. **PHP (fetch_rewards.php)**: Create a PHP script to fetch rewards from the database based on the user ID.


```php

<?php

// Establish a database connection (replace with your actual database connection details)

$servername = "your_server";

$username = "your_username";

$password = "your_password";

$database = "your_database";


$conn = mysqli_connect($servername, $username, $password, $database);


if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

}


if (isset($_GET["user_id"])) {

    $user_id = $_GET["user_id"];


    // Query the database to fetch the user's rewards

    $sql = "SELECT reward_amount FROM user_rewards WHERE user_id = $user_id";

    $result = mysqli_query($conn, $sql);


    $rewards = [];


    if ($result) {

        while ($row = mysqli_fetch_assoc($result)) {

            $rewards[] = $row["reward_amount"];

        }

    }


    // Return rewards as JSON

    echo json_encode($rewards);

}


// Close the database connection

mysqli_close($conn);

?>

```


With this setup, when a user enters a user ID, the JavaScript code will trigger an AJAX request to `fetch_rewards.php`, which will query the database for rewards associated with that user ID. The PHP script will return the rewards as JSON, and the JavaScript code will populate the dropdown menu with these rewards.

Previous
Next Post »