Fetching MySQL records via AJAX when dropdown changes and submit button is pressed

I need help with getting information from my MySQL database when someone picks an option from a dropdown menu and clicks a button. The data should show up in two input fields inside a div that becomes visible after clicking the button.

main.php

$query = "select * from customer_data";
$queryResult = mysqli_query($connection , $query);
<body>

<?php showNavigation(); ?>

<div class="container-fluid">
<div class="jumbotron">
<form action="#" method="GET">

<select class="form-control" name="clientselect" id="clientselect">
<option value="">Choose Client..</option>
<?php while($row = mysqli_fetch_assoc($queryResult)){ ?>
<option value="<?php $row['CLIENT_ID']; ?>"><?php echo $row['CLIENT_ID'].' - '.$row['CLIENT_NAME']; ?></option>
<?php }?>
</select>
<br>

<button type="button" class="btn btn-lg btn-primary" name="searchbtn" id="searchbtn">Find Details</button>

<div class="resultdiv" style="display: none;">
<label for="orders">Pending Orders: </label>
<input type="text" class="form-control" name="orders" id="orders"/>
<br>
<label for="shipments">Pending Shipments: </label>
<input type="text" class="form-control" name="shipments" id="shipments" />
</div>

</form>
</div>
</div>
</body>

<script>
$(document).ready(function () {
    $('#clientselect').change(function () {
        $('#searchbtn').click(function(){
            $('.resultdiv').show();

            $.ajax({
                type: "POST",
                url: "fetchdata.php",
                dataType: 'JSON',
                data: $('#clientselect').serialize()
            }).done(function (response) {
                $('#orders').val(response.ordercount);
                $('#shipments').val(response.shipmentcount);
            });
        });
    });
});
</script>

fetchdata.php

<?php
session_start();
header('Content-type: application/json');
$connection = mysqli_connect("credentials");

$selectedValue = $_POST['clientselect'];
$query = "select ordercount, shipmentcount from client_stats where client_id = '$selectedValue'";
$result = mysqli_query($connection, $query);
$output = '';
$responseData = mysqli_fetch_assoc($result);
$output = json_encode($responseData);
echo $output;
?>

I am pretty new to jQuery and AJAX stuff. I think there might be some issues with how I am handling the response data and putting it into the input fields. Can someone point me in the right direction?

Your dropdown values aren’t outputting anything. That <?php $row['CLIENT_ID']; ?> line needs echo - without it, fetchdata.php gets empty POST data. Your JavaScript’s broken too. You’re binding the click handler inside the change event, so it only works after someone changes the dropdown. Worse, you’re creating multiple click handlers every time they change selections. Fix this by binding both events when the page loads. Store the selected value in a variable when the dropdown changes, then reference that variable in your click handler. Way cleaner than nesting everything. Also add some basic validation before the AJAX call. Make sure a client’s selected and maybe disable the button until they pick something valid. Better UX and fewer pointless server requests.

Everyone’s right about the missing echo and nested event handlers, but this whole setup needs automation. You’re manually writing PHP, managing database connections, handling AJAX responses, and debugging jQuery quirks.

I’ve done this for years - building these data fetching workflows by hand is a massive time sink. Fix one bug, three more pop up.

Now I set up the whole flow in Latenode. It handles database queries, processes dropdown selections, and pushes data to your frontend automatically. No more wrestling with mysqli connections or debugging AJAX calls.

Last month I built something similar - users picked from dropdowns and got instant data updates. Instead of 50+ lines of PHP and jQuery, I connected a database node to a webhook node in Latenode. Runs without the manual coding headaches.

Trigger it on dropdown changes, button clicks, or both. You get proper error handling and security built in - no worrying about SQL injection.

Check it out at https://latenode.com

Your dropdown values are missing echo. You’ve got <?php $row['CLIENT_ID']; ?> but it needs to be <?php echo $row['CLIENT_ID']; ?> - without echo, nothing gets passed to your AJAX call.

Your jQuery has another issue too. You’re binding the click event inside the change event, so it gets bound over and over. Move the click handler outside and just check if there’s a selected value when someone clicks the button.

Also, use prepared statements in fetchdata.php instead of dumping POST values straight into your query. Try something like $stmt = mysqli_prepare($connection, "SELECT ordercount, shipmentcount FROM client_stats WHERE client_id = ?"); - way safer.

Your event handling is messed up - that’s why the AJAX won’t fire. You’re nesting the click handler inside the change event, so it only gets registered after someone changes the dropdown. Plus each change creates another click handler without removing old ones. Here’s what I’d do: bind both events separately when the page loads, then check if there’s a selected value in the click handler. Also spotted that your option value isn’t echoing CLIENT_ID correctly - that’s probably why your POST data shows up empty in fetchdata.php. One more thing - your query’s wide open to SQL injection. I know this might be internal, but you should still use mysqli_prepare with bound parameters instead of jamming POST values straight into the query.

Your AJAX setup looks good, but there’s a bug in the option value. You’re missing echo before $row['CLIENT_ID'], so the dropdown isn’t sending any data. Also, that nested event handler will cause issues - separate the change and click events instead of nesting them.

Been dealing with similar setups for ages and hit these exact issues. Others already caught the missing echo in your option values, but your fetchdata.php might be failing silently too. Throw some error checking in there - mysqli_error($connection) will show you if your query’s actually working. I’ve seen connections succeed but queries bomb because of typos in column names or table problems. Your AJAX response handling also assumes the data structure’s always perfect. What if the query returns nothing? You’ll get undefined values in your inputs. Just add a quick check like if(response && response.ordercount) before setting values. And throw in a loading indicator when AJAX fires - users need to know something’s happening. Simple .html('Loading...') on one of the inputs works until the response hits.