The scenario is we have a form to search our sales orders by customer, sales contact, date etc... Whenever the user changes the customer, we need to update the data used for the customer contact dropdown list.

We have a JavaScript function call onCustomerChange() which is called whenever the value in our Customer control changes:

function onCustomerChange() {
    // Get the selected customer id
    let customer_id = $('#salesordersearch-customer_id').val();

    // Fetch all the customer sales contacts
    $.ajax({
        url: '/customer/get-contacts',
        type: 'get',
        data: {id: customer_id},
        async: false,
        success: function(data) {

            let contact_dropdown = $('#salesordersearch-contact_id');

            // Rebuild dropdown data for cost centres
            contact_dropdown.empty();
            contact_dropdown.append('<option value="">Select ...</option>');
            $.each(data, function(index, row) {
                contact_dropdown.append('<option value="' + row.id + '">' + row.name + '</option>');
            });
        }
    });
}

This function takes the id of the customer (line 3), then makes a GET Ajax request (line 6 to 10). The Ajax call returns all the customer contacts in a JSON format with the contact id and name (see example json below).

[
   {"id":"1434","name":"Ferne Joseph"},
   {"id":"1434","name":"Gus Pritchett"}
   {"id":"1445","name":"Trevor Bennett"},
]

Finally, line 16 removes all previous select options from the dropdown list, and then the foreach loop (line 18 to 20) adds each contact stored in our JSON object.