Hello,

I hope that I can get an answer for this question.

I have a MYSQL table for charges which contains the following fields: ChargesID, ChargesTitle, OfficialFees and ProfessionalFees. What I need is to make a dropdown list which contain ChargesTitle and upon selection to autofill the OfficialFees and ProfessionalFees. I found the following jquery script and is working fine with a static data only. Any idea to change or update the script to work with php and dynamic data from MYSQL.

<select id="Charges">
    <option value="">Please Select</option>
    <option value="1" data-officialcharges="100" data-professionalcharges="30" >Option 1</option>
    <option value="2" data-officialcharges="200" data-professionalcharges="40" >Option 2</option>
    <option value="3" data-officialcharges="300" data-professionalcharges="60" >Option 3</option>
    <option value="4" data-officialcharges="500" data-professionalcharges="30" >Option 4</option>
    <option value="5" data-officialcharges="600" data-professionalcharges="20" >Option 5</option>
</select>

<div>
    <label>Official Fees</label> <input type="text" name="Cofficialcharges" />
    <label>Professional Fees</label> <input type="text" name="Cprofessionalcharges" />
</div>

    <script type="text/javascript" src="../js/jquery-2.0.2.js"></script>
    <script type="text/javascript">

$('#Charges').change(function() {
    selectedOption = $('option:selected', this);
    $('input[name=Cofficialcharges]').val( selectedOption.data('officialcharges') );
    $('input[name=Cprofessionalcharges]').val( selectedOption.data('professionalcharges') );
});

  </script>

Thank you.

Dani AI

Generated

A clean way to make your dropdown drive those two inputs is to keep the select filled with ChargesTitle (and its ChargesID as the value), then fetch the two fees for the chosen id via a small PHP endpoint that returns JSON. This follows what tobyITguy suggested about using AJAX, but instead of injecting HTML (as in Gideon_1’s example), you return just the data you need, which is simpler and safer.

Client-side (no jQuery required):

<script>
document.getElementById('Charges').addEventListener('change', async (e) => {
  const id = e.target.value;
  const off = document.querySelector('input[name="Cofficialcharges"]');
  const prof = document.querySelector('input[name="Cprofessionalcharges"]');

  off.value = '';
  prof.value = '';
  if (!id) return;

  try {
    const res = await fetch('/api/charges.php?id=' + encodeURIComponent(id), {
      headers: { 'Accept': 'application/json' }
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const data = await res.json();
    off.value = data.official_fees ?? '';
    prof.value = data.professional_fees ?? '';
  } catch (err) {
    console.error(err);
    // optionally show a user-friendly message
  }
});
</script>

Server-side (PDO + prepared statements, JSON response):

<?php
// /api/charges.php
header('Content-Type: application/json; charset=UTF-8');

$pdo = new PDO('mysql:host=YOUR_HOST;dbname=YOUR_DB;charset=utf8mb4', 'USER', 'PASS', [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) { http_response_code(400); echo json_encode(['error'=>'invalid id']); exit; }

$stmt = $pdo->prepare('SELECT OfficialFees, ProfessionalFees FROM charges WHERE ChargesID = ? LIMIT 1');
$stmt->execute([$id]);
$row = $stmt->fetch();

if (!$row) { http_response_code(404); echo json_encode(['error'=>'not found']); exit; }

echo json_encode([
  'official_fees' => (float)$row['OfficialFees'],
  'professional_fees' => (float)$row['ProfessionalFees'],
]);

Tips:

  • Populate the select from MySQL on page load (ChargesID as value, ChargesTitle as label).
  • Consider disabling the inputs or marking them readonly if users should not edit calculated fees.
  • Never trust client-sent fees; always derive totals server-side when saving.

Recommended Answers

All 3 Replies

Yh I agree with todyITguy, learning it will be of great help but if you are in need seriously you can use these ajax codes;

        <script type="text/javascript">
            function load () {
                var xmlhttp = new XMLHttpRequest ();

                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById('ajax').innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open ('GET', 'your_php_file.php', true);
                xmlhttp.send ();
            }
        </script>

Here, you can change the php file url to a get method by getting the values of the input fields you will use for the query. Here you will use something like

`'your_php_file.php?value1='.document.getElementById('input_field1_id').value.'&value2='.document.getElementById('input_field2_id').value`

So the onchange event will send the input fields asynchronously to the php file which will perform the query and send it back to the current page.

So don't forget to create an empty div with the id ajax or anything but i prefer using ajax.

so on the php file you get the values with the $_GET superglobal

so

    $value1 = $_GET['value1'];
    $value2 = $_GET['value2'];

and then you do your query. Everything you echo out or display will be displayed in the ajax div on the current page.

Many Thanks for todyITguy and Gideon_1.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.