Dave Dave - 5 months ago 21
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:
JQUERY SECTION

<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(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;
$("#subloc").html(ps);

});
});
});
</script>


FrontEnd(HTML)

<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<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 };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>


Process-loc.php

if(isset($_POST["loca"])){
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'];


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

}
?>


This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.

Answer
$query   = "
                SELECT 
                    tariff_name
                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>'
     }
     $("#patientSelectState").html(areaOption);