David Mukoro
David Mukoro

Reputation: 467

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.

Upvotes: 1

Views: 4565

Answers (3)

line-segment
line-segment

Reputation: 389

On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input. Now query your database and echo the results in a foreach loop(you can make a tag there only). In the ajax 'success:' catch the data and display it.

//from the database
foreach ($info as $product) 
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}

      //ajax call page
      success: function(result) 
      {
        $("#states").html(result);
      }

http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

Upvotes: 0

Premanand K
Premanand K

Reputation: 632

$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);

Upvotes: 2

cssyphus
cssyphus

Reputation: 40030

You can change your AJAX processor to do this:

Process-loc.php

/* Above code the same */
if(mysqli_num_rows($get)>=0) {
    $out = '<select id="selSubLoc"><option value="">Choose One:</option>';
    foreach($gt AS $loc){
        $seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
        $out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
    }
    $out .= '</select>';
}else{
    $out = 0;
}

echo $out;

And change your front-end code's AJAX routine to be like this:

$.ajax({
    type: "POST",
     url:"process-loc.php",
    data:{loca:selectedloc}
}).done(function(recd){
    $("#subloc").html(recd);
});

The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.

Upvotes: 1

Related Questions