Search code examples
javascriptphphtmldropdownbox

Populate multiple dropdownlists from sql and previous selected value


I have code in php to query database and populate records in a dropdown list which a user will pick. I also have javascript which populates the second dropdown list based on the selection of the first box.

How do I tie these two together so user selects value "x" from dropdown list, and the php will query the database "WHERE.... = SselectedValue"

Are there any examples online? I can't seem to find any.


Solution

  • Write an ajax/phpquery call to second dropdown on change method of first dropdown. Eg-

    $("#firstDdwn").on('change',function(){
       var val=$(this).val();
       //php will query the database "WHERE.... = val"
      //on success of data received from query, populate second dropdown
    
    })
    

    Ajax code is supposed to look something like this-

    $.ajax(
    {
          url:"your_controller_URL",
          data: val
          success:function(result){
          //populate 2nd dropdown with result
        },
        error:function(){
          alert("No data received");
         }
    });
    

    Link for brief info on jquery ajax --- http://www.w3schools.com/jquery/ajax_ajax.asp