I have two tables in db named department (contains department) and sup (contains name of supervisors name).
now my query is:

By selecting the department in select menu the next select field sup should automatically get fetched with names.
how can i do it with php using onchange javascript menu..

thanks in advance

Dani AI

Generated

@szjarun833 wanted the supervisors select to update when a department is chosen; suggested an asynchronous request. The pattern below is a modern, secure variant that avoids page reloads: the client uses the Fetch API, the server is a small PHP endpoint that returns JSON, and the PHP side uses prepared statements and input validation.

Client (modern, no jQuery):

// dept select id="dept", sup select id="sup"
const dept = document.getElementById('dept');
const sup = document.getElementById('sup');
let controller = null;

dept.addEventListener('change', async () => {
  const id = dept.value;
  sup.innerHTML = ''; // clear
  const loading = document.createElement('option');
  loading.textContent = 'Loading...'; loading.disabled = true; loading.selected = true;
  sup.appendChild(loading);

  if (controller) controller.abort();
  controller = new AbortController();

  try {
    const res = await fetch('/get-supervisors.php?dept_id=' + encodeURIComponent(id), { signal: controller.signal });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const list = await res.json(); // expect [{id, name}, ...]
    sup.innerHTML = '';
    if (!list.length) {
      const opt = document.createElement('option');
      opt.textContent = 'No supervisors found'; opt.disabled = true;
      sup.appendChild(opt);
    } else {
      for (const r of list) {
        const o = document.createElement('option');
        o.value = r.id; o.textContent = r.name;
        sup.appendChild(o);
      }
    }
  } catch (e) {
    sup.innerHTML = '';
    const opt = document.createElement('option');
    opt.textContent = 'Error loading'; opt.disabled = true;
    sup.appendChild(opt);
    console.error(e);
  }
});

Server (PHP, PDO, minimal):

<?php
header('Content-Type: application/json; charset=utf-8');
if (!isset($_GET['dept_id']) || !ctype_digit($_GET['dept_id'])) { http_response_code(400); echo json_encode([]); exit; }
$dept = (int) $_GET['dept_id'];
$pdo = new PDO('mysql:host=localhost;dbname=DB;charset=utf8mb4','user','pass',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('SELECT id, name FROM sup WHERE department_id = :d ORDER BY name');
$stmt->execute(['d'=>$dept]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

Troubleshooting & notes:

  • Server must return valid JSON and set Content-Type.
  • Validate inputs server-side (never trust client).
  • If endpoint is cross-origin, add appropriate CORS headers.
  • Use an index on the department_id column for performance.
  • Consider debouncing the change handler or caching small lists if departments are switched rapidly.

Recommended Answers

All 2 Replies

One of the simplest methods is to use jQuery's Ajax method to do this.

https://api.jquery.com/jQuery.ajax/

Example code -> not tested

$.ajax({
  url: "your_link.html",
  cache: false,
  success: function(data){
    // you can do an each sequence to append every value to the 
    // select box as options
    // I would respond with a json for the beginning
    // and iterate over every element so you can build your dropdown

    $("#your_select_box").html();
    $.each(data, function( key, value ) {
        $("#your_select_box").append("<option value='" + key + "'>" + value + "</option>");
    }
  }
});

Forgot to add after the url parameter the data: data, parameter so you can send your values to extract exactly what you need.

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.