NEWWPDEV NEWWPDEV - 16 days ago 5
Ajax Question

Populate checkboxes based on dropdown selection

In a form, I do have a list of industries populated from db. I want to populate a list of checkboxes based on the selected industry.

I tried the below but its not working. Can you please help. I am still learning to code and would really appreciate your help.

index.php

// The dropdown is populated from DB
<select class="set_industry">
<option value="1">Healthcare</option>
<option value="2">Food & Beverage</option>
<option value="3">Real Estate</option>
</select>
// Preferably the selection would produce var $ind_id
.
.
.
.
// I want the below to be executed based on the selection from above

<?php
if(isset($_POST['id'])) {
$ind_id = $_POST['id'];
$x="SELECT * FROM srv_tbl WHERE ind_id=$ind_id";
$res=query($x);

while ($y=mysqli_fetch_array($res)) { ?>
<div>
<label>
<input type="checkbox" value="<?php echo $y['srv_id'] ?>"> <?php echo $y['srv_name'] ?>
</label>
</div>
<?php }
} ?>

<script>Link to js script</script>


script.js

$(".set_industry").on('change', function(){
var ind_id = $(this).attr("value");
$.post("index.php", {id: ind_id}, function());
});

Answer

Separate your PHP code .

index.php

<?php 

if(isset($_POST['id'])) {

  $ind_id = $_POST['id'];
  $x="SELECT * FROM srv_tbl WHERE ind_id=$ind_id";
  $res=query($x);

  $returnString = '';   
  while ($y=mysqli_fetch_array($res)) {

     $returnString .= '<div><label><input type="checkbox" value=".$y['srv_id'].">.$y['srv_name'].</label></div>';
  }

  echo $returnString;
} ?>

add new div to your HTML page

index.html

<select class="set_industry">
    <option value="1">Healthcare</option>
    <option value="2">Food & Beverage</option>
    <option value="3">Real Estate</option>
</select>

<div id="response"></div>

<script>Link to js script</script>

Do these changes to your script.js

$(".set_industry").on('change', function(){ 
    var ind_id = $(this).attr("value");
    $.post("index.php", {id: ind_id}, function(data){

       $("#response").html( data );
    });  
});
Comments