0

Right now I am using a static array in my javascript and I would like to change it to get the info from my MariaDB table. I have one radio select (yes/no) that should determine which entries are selected to populate the select field, if yes, get the DB results for A, B, C, if no, get X, Y, Z.

<script type="text/javascript">    
$(function() {
  var primaryDisposition = {
    1: ['A', 'B', 'C'],
    2: ['X', 'Y', 'Z']
  };
  $('#radioDispositionGroup input[type=radio]').click(function(){      
        var options = '<option disabled selected>Choose one</option>';
        $.each(primaryDisposition[$(this).val()] || [], function(i, v) {
              options += '<option>' + v + '</option>';
        });
        $('select[name="selectDisposition"]').html(options);
    });
});
</script>

EDIT: I switched to using ajax, even though fetch would work just as well. I do have a question, the following does get the data I want, but I am not sure on the best way to make it so when I click on the radio Yes it will populate the select field.

$(function() {
    $.ajax({
        method: 'GET',
        url: "/dispositions",
        success: function(data){                
            let primaryDisposition = data;
            $('#radioDispositionGroup input[type=radio]').click(function(){
                let options = '<option disabled selected>Choose one</option>';
                $.each(primaryDisposition, function(i, v) {
                    options += '<option value="'+ v.id +'">' + v.description + '</option>';
                });
                $('select[name="selectDisposition"]').html(options);
                });
            console.log('Success0 '+ data[0].description); //using data[0] so I can see the test data
        }
    });
});
Dyasis
  • 61
  • 7

1 Answers1

0

If you want to use something like fetch to get a javascript array to work with like you are doing on your code then you can use this example for your php page: JSON encode MySQL results

Your fetch code would look something like:

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function(data) {
    // Your code for handling the data you get from the API
    let primaryDisposition = JSON.parse(primaryDisposition)
    $('#radioDispositionGroup input[type=radio]').click(function(){      
        var options = '<option disabled selected>Choose one</option>';
        $.each(primaryDisposition[$(this).val()] || [], function(i, v) {
            options += '<option>' + v + '</option>';
        });
        $('select[name="selectDisposition"]').html(options);
    });
})
.catch(function() {
    // This is where you run code if the server returns any errors
});
FroboZ
  • 437
  • 1
  • 6
  • 17