I guess you can do this:
make a global function which accepts two args, currElem, nextElem
and dataObj
:
function dynoDropdowns(currElem, nxtElem, dataObj){
$.ajax({
url:"path/to/file",
type:"post",
data:dataObj,
dataType:"json", // <-------------expecting json from php
success:function(data){
$(nxtElem).empty(); // empty the field first here.
$.each(data, function(i, obj){
$('<option />',
{
value:obj.value,
text:obj.text
}
).appendTo(nxtElem);
});
},
error:function(err){
console.log(err);
}
});
}
now your change events are:
$(function(){
$('select').on('change', function(e){
if(this.id === "id"){
var dataObj = {id:this.value};
dynoDropdowns(this, '#name', dataObj);
}else if(this.id === "name"){
var dataObj = {name:this.value};
dynoDropdowns(this, '#department', dataObj);
}
});
});