Creating a Dependent Dropdown List with PHP, jQuery and Ajax.

There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. Scenarios like this can be populating a Country’s State dropdown based on the value of the Country selected, populating product sub-categories based on the parent category. In this example, we will be creating a dropdown list for category/subcategory for a product in an eCommerce website.
Create a database called dependent_list.

We will Create 2 tables: categories and subcategories with the following queries:

CREATE TABLE IF NOT EXISTS `categories` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `subcategories` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`categoryID` INT(11) NOT NULL,
`subcategory_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Some data has been inserted into both tables as shown in database. categoryID is a foreign key in subcategories table i.e 1 category has multiple subcategories.

Create a project folder called ‘dependent_list’ in your site root folder. Create a config.php file to store the database connection and add the following code:

  1. <?php
  2. mysql_connect(‘localhost’, ‘root’, );
  3. mysql_select_db(‘dependent_list’);
  4. ?>

Next Create an index.php file in the project folder and add the following code:

  1. <?php
  2. include(‘config.php’);
  3. $query_parent = mysql_query(“SELECT * FROM categories”) or die(“Query failed: “.mysql_error());
  4. ?>
  1. <!doctype html>
  2. <meta charset=“utf-8”>
  3. <title>Dependent DropDown List</title>
  4. <script type=“text/javascript” src=“js/jquery.js”></script>
  5. <script type=“text/javascript”>
  6. $(document).ready(function() {
  7. $(“#parent_cat”).change(function() {
  8. $(this).after(‘<div id=“loader”><img src=“img/loading.gif” alt=“loading subcategory” /></div>‘);
  9. $.get(‘loadsubcat.php?parent_cat=’ + $(this).val(), function(data) {
  10. $(“#sub_cat”).html(data);
  11. $(‘#loader’).slideUp(200, function() {
  12. $(this).remove();
  13. });
  14. });
  15. });
  16. });
  17. </head>
  18. <form method=“get”>
  19. <label for=“category”>Parent Category</label>
  20. <select name=“parent_cat” id=“parent_cat”>
  21. <?php while($row = mysql_fetch_array($query_parent)): ?>
  22. <option value=“<?php echo $row[‘id’]; ?>“><?php echo $row[‘category_name’]; ?></option>
  23. <?php endwhile; ?>
  24. <br/><br/>
  25. <label>Sub Category</label>
  26. <select name=“sub_cat” id=“sub_cat”></select>
  27. </form>
  28. </body>
  29. </html>

On line 3, we queried our categories table to get all categories. We then populate the parent_cat dropdownlist with the categories on lines 33-37. Whenever the dropdown value for category is changed, a jquery changed event is triggered for the category dropdown list on line 10. On lines 10-18,it sends the id value of the selected category through jquery Ajax to a php script called loadsubcat.php which then queries the subcategories table for subcategories that belongs to the parent category id value using $_GET[] super global . The values returned is now appended to the sub_cat dropdown list. We also added an animated loading gif for user experience, it is displayed when the a value is selected for the parent category and removed using a jquery “slideUp” method after the subcategory has been populated.

Lastly, create a loadsubcat.php file in the project folder and add the following code.

  1. <?php
  2. include(‘config.php’);
  3. $parent_cat = $_GET[‘parent_cat’];
  4. $query = mysql_query(“SELECT * FROM subcategories WHERE categoryID = {$parent_cat});
  5. while($row = mysql_fetch_array($query)) {
  6. echo “<option value=’$row[id]‘>$row[subcategory_name]</option>”;
  7. }
  8. ?>

Now go to http://localhost/dependent_list and you will see how the dependent dropdownlist works

Source: http://www.sourcecodester.com/tutorials/php/5568/creating-dependent-dropdown-list-php-jquery-and-ajax.html

 

 

Refresh form but do not resubmit (PHP)

This question has been asked so many times that most of you don’t want to hear it again. Unfortunately, the solutions that people are proposing are less than ideal.

For those who are new to the concept, a quick explanation is in order. You have a form that you display, validate and act upon (send e-mail, save to database, upload files, etc.) Once this is done, the user might refresh the page and you will end up with duplicate entries.

Bad ideas to handle it are: splitting into multiple files to work around this problem, using the meta-refresh tag, setting unique identifiers and store them in session or in hidden fields, checking for duplicates after resubmission, using javascript…
If you want to know why they are bad, just post a comment and I will give you a detailed explanation of the particular case.

I found a quick and neat way to do it (perhaps I’m not the first, but I feel the need to share it). Append “?submit=true” to your form action and use header(“Location: …”) with the current URL. Thus, once form data has been saved, you will be redirected to the same page without the POST variables. If PHP complains that output was already sent, then you have a bad approach for your output. I usually store all my output in a variable(s) and echo it when everything is okay. More on output in another entry.

Example:

 <form class=”form-horizontal” role=”form” method=”post” action=”../add?submit=true”>

 

Then

header(‘Location: http://www.example.com/&#8217;);

 

Source: http://afilina.com/refresh-form-but-do-not-resubmit-php/comment-page-1/