Search code examples
ajaxselectlive

Get select information before submitting


well i was reading around the solutions that stack-overflow was giving but i couldn't find the correct one... so here is my question:

Im creating a form with multiple selects ( not the select multiple="true" ) , no , i mean a form with lets say 4 different selects... retrieving data from a database so if i fill my first "select" lets say Style1 then i would like to get the "style1" selection so i can configure my second select query based on that and i can DISTINCT the values im looking for... i don't know if you get my idea, i've read i need to use AJAX but i couldn't figure out how to...


<form method="post">
<select name="category">
<?php $test = mysql_query("SELECT category FROM test_table GROUP BY category");
while($testing = mysql_fetch_array($test)){
echo "<option value=".$testing["category"].">".$testing["category"]."</option>";
}
?>
</select>
<select name="model">
<?php $test2 = mysql_query("SELECT model FROM test_table WHERE model = 'TRYING TO COMPARE WITH THE VALUE WITH THE FIRST SELECT' GROUP BY model");
while($testing2 = mysql_fetch_array($test2)){
echo "<option value=".$testing2["model"].">".$testing2["model"]."</option>";
</select>
</form>

Well that was just to get an idea, is not like the real one but its a pretty close example.

  1. Sorry for my weird spelling
  2. Thanks for your help !

Solution

  • <form method="post">
        <select name="category" onchange="javascript:getDroupDownValues(this.value);">
        <?php $test = mysql_query("SELECT category FROM test_table GROUP BY category");?>
        <?php while($testing = mysql_fetch_array($test)):?>
            <option value="<?php echo $testing["category"];?>"><?php echo $testing["category"];?></option>
        <?php endwhile;?>
        </select>
        <div id="model-category">
    
        </div>
    </form>
    <script type="text/javascript">
    function getDroupDownValues(value)
    {
    
        jQuery.ajax({
            dataType: "html",
            type: "POST",
            evalScripts: true,
            url: 'your ajax url', // example your site url /ajax.php
            data: ({category:value}),
            success: function(data, textStatus) {            
                jQuery("#model-category").html(data);
            }
        });    
    }
    </script>
    

    Now in ajax.php script

    <?php if(isset($_REQUEST['category']) && $_REQUEST['category']):?>
        <select name="model">
        <?php $test2 = mysql_query("SELECT model FROM test_table WHERE model = '{$_REQUEST['category']}' GROUP BY model");?>
        <?php while($testing2 = mysql_fetch_array($test2)):?>
            <option value="<?php echo $testing2["model"];?>"><?php echo $testing2["model"];?></option>
        <?php endwhile;?> 
      </select>    
    <?php endif;?>