Select related to another select, pulling data from the database

Asked

Viewed 438 times

0

I need to create a form that pulls the options from the sql database. So far so good, I did a while inside a query in php;

echo '<SELECT NAME = "setor">';
    while ( $temp = $setores->fetch_assoc() ) {
        echo '<OPTION>'.$temp['nome'];  
    } 
echo '</SELECT>';

But I need a second select to only display the information according to the selected option in the first select.

So for example, if in this select the user select '''movies', the next select should display the existing movies in the database, if it select ''series', it returns the registered series, and so on.

What’s the simplest way I could do it?

  • The project has Jquery or javascript only?

1 answer

-1


In the onChange event of your select, create a method and do an ajax search to popular the second select.

Something like this:

$('.select1').on('change', function(){

    var id = $(this).val();

    $.ajax({
        url: 'url',
        data: {
            id: id
        },
        type: 'GET',
        dataType: 'json',
        success: function(data){

            var html = '';

            $.each(data, function(){
                html += "<option value='"+this.id+"'>"+this.texto+"</option>";
            });

            $('.select2').html(html);
        }
    })

})

Remember that in PHP you should return a json to JS:

echo json_encode($arrRetorno);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.