Dave Dave - 7 months ago 32
Ajax Question

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:

<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;



<th>Primary Location:</th>
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
<th>Sub Location:</th>
<td id="subloc"></td>


include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';

$main = $_POST["loca"];

$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);

//$nos= $gt['opsNo'];

echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
echo json_encode(array("res"=>"0"));


This is what I wants to be displayed on the Front End page for the use:
How can I achieve this.

$query   = "
                FROM tariff_setting";
        $result = mysqli_query($this->_connection, $query);

       while ($row = mysqli_fetch_assoc($result)) 
            $response[] = $row['tariff_name'];

$tarrifList = json_encode($response);

// $tarrifList is the response and sent it in json encode format and decode on ajax success

// Javascript Process

 var obj = JSON.parse(resdata);
    var areaOption = "<option value=''>Select State</option>";
     for (var i = 0; i < obj.length; i++) {
         areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'