planet x
planet x

Reputation: 1607

php ajax two select box

I am quite new to this jquery ajax. What I want to know is how can I populate the content of my second select box based on the selection from the first select box. Say here is my HTML:

<form method="post" action="tosomewhere.php">
<table>
<tbody>
<tr>
  <td>
    <select id="first" name="year">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  </td>
</tr>
<tr>
  <td>
    <select id="second" name="section">
    </select>
  </td>
</tr>
</tbody>
</table>
</form>

The jscript:

<script type="text/javascript">
$(function () {
$("#first").change(function () {
$("#second").load('second_option.php?year=', {first: $(this).val()});
});
});
</script>

The PHP file:

<?php

require '../../config/dbconfig.php';
$year = $_GET['year'];
$sql = "SELECT * FROM section_tb WHERE year = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($year));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$second_option = "";
foreach($result as $key => $value)
    $second_option .= "<option value='".$value['section_name']."'>".$value['section_name']."</option>";
echo $second_option;
?>

The content of my second select box will be populated from a mysql results of WHERE value of first select box. I can build the PHP file, I'm just confuse on how to return and populate it on the select.

Any leads to tutorials or samples? Thank you so much.

EDIT: Added the jquery script, but still no luck. I tried to var_dump($second_option) it has contents.

Upvotes: 0

Views: 4657

Answers (2)

Jake Feasel
Jake Feasel

Reputation: 16955

Add this javascript to your current page:

<script>
$(function () {

  $("#first").change(function () {
    $("#second").load('second_options.php?year=' + $(this).val());
  });

});
</script>

And return this content in your "second_options.php":

  <option value="1">a</option>
  <option value="2">b</option>

Upvotes: 1

Kishore
Kishore

Reputation: 1912

here are some tutorials

www.huanix.com/files/dependent_select/dependent_select.php

http://bytes.com/topic/php/answers/708593-dependent-dropdown-list-mysql

http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php

Upvotes: 0

Related Questions