Dynamic select field according to 2 other select fields selection

This public forum is for user-to-user discussions of PHPMaker. Note that this is not support forum.
Post Reply
noremote
User
Posts: 9

Dynamic select field according to 2 other select fields selection

Post by noremote »

Dynamic select field according to 2 other select fields selection

I am in PHPMaker 2024
in my add page (casesAdd.php) the 3 select field names are
x_drop_requested, x_drop_atoll and x_drop_selectedby
x_drop_selectedby should by dynamically changing according to the selection of x_drop_requested and x_drop_atoll.

i have tested the function with standalone pages with

casesAdd_page_script.php

    <script src="jquery/jquery.min.js?v=24.5.7"></script>
    
    <script>
$(document).ready(function() {
    // Function to fetch options based on selected values
    function fetchOptions(selectedRequested, selectedAtoll) {
        $.ajax({
            type: "POST",
            url: "4mycust_selectedby.php",
            data: {
                selectedRequested: selectedRequested,
                selectedAtoll: selectedAtoll
            },
            success: function(response) {
                $("#x_drop_selectedby").empty().append(response);
                console.log("Received options:", response);
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
            }
        });
    }

    // Event listener for x_drop_requested change
    $("#x_drop_requested").change(function() {
        var selectedRequested = $(this).val();
        var selectedAtoll = $("#x_drop_atoll").val();
        
        // Make sure selectedRequested and selectedAtoll are not empty
        if (selectedRequested && selectedAtoll) {
            // Fetch options based on selected values

            fetchOptions(selectedRequested, selectedAtoll);
        }
    });

    // Event listener for x_drop_atoll change
    $("#x_drop_atoll").change(function() {
        var selectedRequested = $("#x_drop_requested").val();
        var selectedAtoll = $(this).val();
        
        // Make sure selectedRequested and selectedAtoll are not empty
        if (selectedRequested && selectedAtoll) {
            // Fetch options based on selected values
            fetchOptions(selectedRequested, selectedAtoll);
        }
    });
});
</script>


<select id="x_drop_requested" name="x_drop_requested">
    <option value="">Select Option</option>
    <option value="z_gov">GOV</option>
    <option value="z_councils">COUNCIL</option>
    <option value="z_schools">SCHOOL</option>
    <!-- Add other options here -->
</select>

<select id="x_drop_atoll" name="x_drop_atoll">
    <option value="1">HA (Thiladhunmathi Uthuru)</option>
    <option value="2">HDh (Thiladhunmathi Dhekunu)</option>
    <!-- Add atoll options here -->
</select>

<select id="x_drop_selectedby" name="x_drop_selectedby">
    <option value="">Select Selected By</option>
    <!-- This will be populated dynamically based on selection -->
</select>

4mycust_selectedby.php

<?php
error_log("POST Data: " . print_r($_POST, true));

// Include the database connection file
require_once "1my_config.php";

// Check if the key exists in $_POST
$selectedRequested = isset($_POST['selectedRequested']) ? $_POST['selectedRequested'] : '';
$selectedAtoll = isset($_POST['selectedAtoll']) ? $_POST['selectedAtoll'] : '';

// Create a function to get the options based on the selected values
function getOptions($selectedRequested, $selectedAtoll) {
    global $my_conn;

    // Escape the values to prevent SQL injection
    $selectedRequested = mysqli_real_escape_string($my_conn, $selectedRequested);
    $selectedAtoll = mysqli_real_escape_string($my_conn, $selectedAtoll);

    // Check if $selectedAtoll is not empty before executing the query
    if (!empty($selectedRequested) && !empty($selectedAtoll)) {
        // Determine the table name based on the selected option
        switch ($selectedRequested) {
             case 'z_gov':
                $table = 'z_gov';
                break;
            case 'z_councils':
                $table = 'z_councils';
                break;
            case 'z_schools':
                $table = 'z_schools';
                break;
            case 'z_ngo':
                $table = 'z_ngo';
                break;
            case 'z_combiz':
                $table = 'z_combiz';
                break;
            case 'z_International':
                $table = 'z_individual';
                break;
            case 'International':
                $table = 'z_International';
                break;
            case 'z_resort_hotel':
                $table = 'z_resort_hotel';
                break;
            case 'NILL':
                // For NILL option, return an empty string
                return '';
            default:
                // If none of the above options match, return an empty string
                return '';
        }

        // Modify the SQL query to use the determined table
        $sql = "SELECT name FROM $table WHERE id_atoll = '$selectedAtoll'";

        error_log("SQL Query: " . $sql); // Log the SQL query

        // Execute the SQL query
        $result = mysqli_query($my_conn, $sql);

        // Check for errors
        if (!$result) {
            error_log("Error in SQL query: " . mysqli_error($my_conn));
            die("Error in SQL query: " . mysqli_error($my_conn));
        }

        // Check if any rows are returned
        if (mysqli_num_rows($result) == 0) {
            error_log("No options found for the given criteria.");
            return '';
        }

        $options = ''; // Initialize options variable

        while ($row = mysqli_fetch_assoc($result)) {
            $option = htmlspecialchars($row['name']);
            $options .= "<option value='$option'>$option</option>";
        }

        // Free result set
        mysqli_free_result($result);

        error_log("Retrieved Options: " . $options); // Log the retrieved options

        // Echo options directly
        echo $options;
    }
}

// Call the function with the provided values
getOptions($selectedRequested, $selectedAtoll);

// Close the database connection
mysqli_close($my_conn);
?>

When i add the casesAdd_page_script just below the view/casesAdd.php and keep the 4mycust_selectedby.php in the root directory, i get the following error

POST http://localhost/j9ptl_cases2/api/lookup?q=&n=100&rnd=114003&start=-1 401 (Unauthorized)

Warning: Undefined array key "page" in D:\xampp8.2.12\htdocs\j9ptl_cases2\src\ApiPermissionMiddleware.php on line 97

Warning: Undefined array key "field" in D:\xampp8.2.12\htdocs\j9ptl_cases2\src\ApiPermissionMiddleware.php on line 98

please help


arbei
User
Posts: 9384

Post by arbei »

noremote wrote:

When i add the casesAdd_page_script just below the view/casesAdd.php and keep the 4mycust_selectedby.php in the root directory

If you try to access the script by /views/casesAdd_page_script.php, your Ajax URL will be /views/4mycust_selectedby.php. It will not work. The error you posted is for lookup via API, it should not be raised by your own script and should be unrelated.


noremote
User
Posts: 9

Post by noremote »

I changed the directory as /views/casesAdd_page_script.php still does not work. the error is
POST http://localhost/j9ptl_cases2/api/lookup?q=&n=100&rnd=134935&start=-1 401 (Unauthorized).

What is the solution for. the strange thing is when i execute the script in stand alone pages it works fine. How can i implement this function in my project.
Please help


arbei
User
Posts: 9384

Post by arbei »

arbei wrote:

The error you posted is for lookup via API, it should not be raised by your own script and should be unrelated.

You are accessing your own standalone scripts. They will not trigger the API lookup action. You better press F12 in your browser and check the HTTP request and response to and from your own scripts.


noremote
User
Posts: 9

Post by noremote »

is that means i cannot implement this function to phpmaker.

please guide me


arbei
User
Posts: 9384

Post by arbei »

Of course you can, problem is your scripts are standalone (you did not "implement this function to phpmaker" with any code), if you use them standalone too (accessing the scripts directly by URL), it is not related to PHPMaker scripts in any way.

If you tried to integrate your scripts in PHPMaker scripts, your code did not show (your code did not access /api/lookup at all). If you meant the you added your <script> to the original casesAdd.php, and the fields are lookup fields (with lookup table or user values), you code will not work because it breaks the original JavaScript for lookup. If you want to use your own <select> tag, you should use Custom View Tag and do not set up any lookup settings.


noremote
User
Posts: 9

Post by noremote »

Can you please tell me how to achieve this function (dynamically updating a select field according to 2 other select fields)
By using Custom View Tag is also ok, but i could not figure out.
Or else... by giving access to api/lookup to my own script.. (how)

Thank you in advance


mobhar
User
Posts: 11726

Post by mobhar »

Have you tried Dynamic Selection List?


noremote
User
Posts: 9

Post by noremote »

yes I have tried Dynamic Selection List which only allowed me to lookup from 1 table 1 select field


arbei
User
Posts: 9384

Post by arbei »

noremote wrote:

By using Custom View Tag is also ok, but i could not figure out.

You better read Custom View Tag and try, it is simple to use own HTML tag, as the docs said:
You can enter your code directly. Click the [...] button to enter your own code to display the your data in your own PHP, HTML and JavaScript.


mobhar
User
Posts: 11726

Post by mobhar »

noremote wrote:

yes I have tried Dynamic Selection List which only allowed me to lookup from 1 table 1 select field

Dynamic Selection List should be able to use with more than one field. All you need to do is by setup the Parent and Filter field from the Lookup Table.


Post Reply