Ansh Ansh - 1 month ago 8
Ajax Question

Cannot get corresponding value from one select box

I am working on a registration page where a user when selects its designation, its corresponding reporting head gets selected in "reporting head" field dynamically. I have used Ajax for this but somehow the reporting head field remains empty. Can I get some insights over this?? It will be highly appreciated.

Here goes my registration fields,

<select name="designation" class="form-control" required="" id="desig" >
<option selected="selected" >Select your option</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl_designation where id in (1,2,3,4)");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value=" . $row['id'] . ">" . $row['designation'] . "</option>";
}
?></select>

<select name="reporting_head" class="form-control" required="" id="rephead">
<option selected="selected">Select your option</option>
</select>


Now JavaScript+AJAX that I am applying,

$(document).ready(function()
{
$("#desig").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "ajax_rep.php",
data: dataString,
cache: false,
success: function(html)
{
$("#rephead").html(html);
}
});
});
});


And finally my ajax_rep.php

<?php

require("includes/config.php");
require("classes/Database.class.php");

if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("SELECT reporting_head_id, reporting_head FROM `tbl_designation` WHERE id='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>


This is the HTML I am getting on ajax success,

<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<option value="6">Sales Head</option>

Answer Source

try this in you loop while

    $list = '<option selected="selected">Select your option</option>';


while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
$list .= '<option value="'.$id.'">'.$data.'</option>';
}
}

echo $list;

And in your ajax success function do this

success: function(html)
{
  $("#rephead").html("");
  $("#rephead").append(html);
}