Skip to content
Advertisement

Dropdown onchange calling PHP Function

What I’m attempting to do with the below code is call a PHP function from an drop-down menu.

Is there a clean way of doing this?

code:

<html>
<head>
</head>
<body>
    <?php
        function OnSelectionChange() {
            echo("OK IT WORKS");
        }    
    ?>
<section>
    <select onchange="OnSelectionChange()">
        <option value='' disabled selected>Assign Driver</option>
        <option value='4353'>Steve Jobs</option>
        <option value='3333'>Ian Wright</option>
        <option value='66666'>Mark James</option>
    </select>
</section>    
</body>
</html>

Advertisement

Answer

simple ajax using jquery

index page

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
            $('#myDropDown').change(function(){
                //Selected value
                var inputValue = $(this).val();
                alert("value in js "+inputValue);

                //Ajax for calling php function
                $.post('submit.php', { dropdownValue: inputValue }, function(data){
                    alert('ajax completed. Response:  '+data);
                    //do after submission operation in DOM
                });
            });
        });
        </script>
    </head>
<body>
    <select id="myDropDown">
        <option value='' disabled selected>Assign Driver</option>
        <option value='4353'>Steve Jobs</option>
        <option value='3333'>Ian Wright</option>
        <option value='66666'>Mark James</option>
     </select>

</body>
</html>

in submit.php

<?php
function processDrpdown($selectedVal) {
    echo "Selected value in php ".$selectedVal;
}        

if ($_POST['dropdownValue']){
    //call the function or execute the code
    processDrpdown($_POST['dropdownValue']);
}

for simple js ajax use XMLHttpRequest

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement