Skip to content Skip to sidebar Skip to footer

Change Ajax Post Parameters & Returned HTML Based On Alternating Dependant Dropdowns

I have 3 dropdowns containing values that are populated on page load

Solution 1:

This one should work for JS side, you will have to check mapping function for response

$('#make, #model, #version').change(function(ev){
    let selected = $(this).val();
    let id = ev.target.id;
    let data = {};
    data[id] = selected;
    $.ajax({
        url: 'php/dropdown.php',
        type: 'POST',
        data: data,
        success:function(data)
        {  
           let options = ['make', 'model', 'version']
           const response = {
             make: JSON.parse(data[0].map(make => make.mMake)),
             model: JSON.parse(data[1].map(make => make.mModel)),
             version: JSON.parse(data[2].map(make => make.mVersion))
           }

           options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
        }
    });
});
function setDropdown(id, data) {
    const id = `#${id}`
    $(id).html('');
    for (let i = 0; i < data.length; i++) {
        if (data[i] != '' && data[i] != null) {
                $(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
        }
    }
}

Post a Comment for "Change Ajax Post Parameters & Returned HTML Based On Alternating Dependant Dropdowns"