JQuery and Ajax, Cascading selects
This goes into the page :
Source : www.infotuts.com/cascaded-dropdown-jquery-ajax-php
Below is code from index.php that will populate country dropdown from database:
</p> <div id="dropdowns"> <div id="center" class="cascade"> <?php $sql = "SELECT * FROM tbl_country ORDER BY country_name"; $query = mysqli_query($con, $sql); ?> <label>Country: <select name="country" id = "drop1"> <option value="">Please Select</option> <?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC )) { ?> <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["country_name"]; ?></option> <?php } ?> </select> </label> </div> <div class="cascade" id="state"></div> <div id="city" class="cascade"></div> </div> <p style="text-align: justify;">
And this also :
Now main part comes here, we have to show only those states in second dropdown which belong to the country selected in first dropdown.
So we will use jQuery and Ajax to retrieve selected country’s ID and send it to fetch_state.php. Below is our jQuery code:
</p> <script> $(<span id="IL_AD7" class="IL_AD">document</span>).ready(function(){ $("select#drop1").change(function(){ var country_id = $("select#drop1 option:selected").attr('value'); // alert(country_id); $("#state").html( "" ); $("#city").html( "" ); if (country_id.length > 0 ) { $.ajax({ type: "POST", url: "fetch_state.php", data: "country_id="+country_id, cache: false, beforeSend: function () { $('#state').html('<img src="loader.gif" alt="" width="24" height="24">'); }, success: function(html) { $("#state").html( html ); } }); } }); }); </script> <p style="text-align: justify;">