Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....</p> <p>Thanks to <a href="http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/" rel="nofollow">http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/</a> for the tutorial.</p> <p>And thanks to everyone here. </p> <p>PHP to build for the first :</p> <pre><code>function agency_select() { include('../include/dbase.php'); $agencies = $pdo-&gt;query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName"); $opt = ''; while ($age_array = $agencies-&gt;fetch(PDO::FETCH_ASSOC)) { $opt .= '&lt;option value="'.$age_array['AgencyId'].'"&gt;'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'&lt;/option&gt;'."\n\t\t\t\t\t\t\t"; } return $opt; } </code></pre> <p>HTML for the two elements:</p> <pre><code>&lt;label for="AgencyId"&gt;Client/Agency:&lt;/label&gt; &lt;select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden"&gt; &lt;?php echo agency_select(); ?&gt; &lt;/select&gt; &lt;label for="Contact"&gt;Contact: &lt;/label&gt; &lt;select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden"&gt; &lt;option value=""&gt;----Select Client/Agency----&lt;/option&gt; &lt;/select&gt; </code></pre> <p>AJAX file:</p> <pre><code>if(isset($_POST['AgencyId'])) { include('../include/dbase.php'); $option = '&lt;option value=""&gt;----Select Contact----&lt;/option&gt;'; $query = $pdo-&gt;prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName"); $result = $query-&gt;execute(array($_POST['AgencyId']))); while ($row = $result-&gt;fetch(PDO::FETCH_ASSOC)) { $option .= '&lt;option value="'.$row['id'].'"&gt;'.$row['FirstName'].' '.$row['LastName'].'&lt;/option&gt;'; } echo $option; } </code></pre> <p>jQuery:</p> <pre><code>$(document).ready(function () { update_contacts(); }); function update_contacts() { $('#AgencyId').change(function() { $('#Contact').fadeOut(); $('#loader').show(); $.post('../ajax/ajax_contact_select.php', { AgencyId: $('#AgencyId').val() }, function (response) { setTimeout("finishajax('Contact', '"+escape(response)+"')", 400); }); return false; }); } function finishajax(id,response) { $('#loader').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload