Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What I do in such scenario is the following:</p> <ol> <li><p>I construct the first dropdownlist on the server, with PHP <code>while</code> over the car categories from the database, for example. I place the <code>id</code> of the category as a <code>value</code> of the <code>option</code>. The resulting HTML should look something like this:</p> <p>&lt;select id="cars-categories"&gt; &lt;option value="1"&gt;Toyota&lt;/option&gt; &lt;option value="2"&gt;Nissan&lt;/option&gt; &lt;option value="3"&gt;Chevrolet&lt;/option&gt; ... &lt;/select&gt;</p></li> <li><p>Then on the page, with JavaScript, I listen for <code>onchange</code> event of the select and when occurs send the category <code>id</code> to the server</p></li> <li><p>PHP code on the server picks the category <code>id</code> and makes a <code>SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']</code>. Send the result as <code>JSON</code> with <code>json_encode</code></p></li> <li><p>Finally, parse the returned data with JavaScritp and fill the model dropdownlist.</p></li> </ol> <p>Here is what the client script basically can look like:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $('#cars-categories').change(function () { $('#car-models option').remove(); $.ajax({ url: "get_data.php", dataType: 'json', data: { category: $('#cars-categories').val() }, async: true, success: function(json){ $.each(json, function(key, value){ $('#car-models').append('&lt;option value="' + value.id + '"&gt;' + value.name + '&lt;/option&gt;'); }); } }); $('#car-models').show(); }); }); &lt;/script&gt; </code></pre> <p>Encoding shouldn't be an issue.</p> <p><strong>EDIT:</strong> As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.</p> <pre><code>&lt;?php // connect to DB ... // initialize an array that will hold the rows $rows = array(); // sanitize the category id. since it is an int, it is safest just to cast it to an integer $cat_id = (int)$_GET['category']; $result = mysql_query("SELECT id, name FROM `models` WHERE cat_id = $cat_id"); while($row = mysql_fetch_assoc()){ $rows[] = $row; } // do a regular print out. It is not going to the screen but will be returned as JavaScript object echo json_encode($rows); // you have to exit the script (or at least should not print anything else) exit; ?&gt; </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