0

I tried to build select box that change, with ajax, the values of the second select box.

First I choose AREA and than the CITIES in this area.

Can you please tell me what do I do wrong?

Client side:

<script>
$(function () {

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

});
</script>


<form method="post" action="tosomewhere.php">

    <select id="first" name="area_id">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>

    <select id="second" name="section">  </select>

</form>

Server side:

<?PHP

    include "db.php"

    $areaID = $_GET['area_id'];
    $second_option = "";

    $query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
    while($index = mysql_fetch_array($query2)) 
    {
        $id = $index['id'];
        $name  = $index['name'];

        $second_option .= "<option value='$id'>$name</option>";
    }

    echo $second_option;

?>
Roi
  • 1
  • 1
  • 6

1 Answers1

0

Try this,

$(function () {

  $("#first").change(function () {
    $.get('recs.php', {area_id: $(this).val()}, function(data) {
      $("#second").html(data);
    });
  });

});

NOTE: It's better to put an exit after echo.

echo $second_option;
exit;
Nikhil Mohan
  • 891
  • 6
  • 13
  • If i was you i would return a json encoded array from the php side and loop it and append it to the select box with jquery. this is much more cleaner. – astroanu Aug 21 '13 at 18:23
  • @NikhilMohan - thanks, but it still not working I seems to be that the SCRIPT part, in the client side, doesn't recieve any results at all... – Roi Aug 22 '13 at 07:23
  • i don't usually use the load method. maybe they might deprecate it in a future version. see this answer http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery sending data as json is much neat-er and after you get the data you can manipulate it with jquery much easily. – astroanu Aug 23 '13 at 07:43
  • @NikhilMohan by "get" i didn't meant the get method. – astroanu Sep 09 '13 at 06:20