dimanche 18 juin 2023

How to send id of a checked checkboxes which contains categories to ajax and show subcategories related to that checked checkbox?

I am successfully send checkbox value which is id of a category when checkbox is checked and show subcategories on thee same page related to selected subcategory but I have a problem when click on multiple categories and again unchecked one of the category all subcategories goes un display. I want to un display the subcategory of only unchecked category when I check and uncheck the values anytime. here is my code hope you get my point thank you

**Ajax **

<script>
function showUser(str) {
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {

        document.getElementById("txtHint").innerHTML += this.responseText;
    
      }
    };

    
    xmlhttp.open("POST","getsubcat.php?q="+str,true);
    xmlhttp.send();
    
  }
}
</script>

J query

 <script>
         
          $(function() {
    //code here
    $('input[type=checkbox]').on('change', function() {
    if($(this).is(':checked')) {
        showUser($(this).val());
    }
    
    
    else{
        
        showUser("");
    }
});
          
         
});
          
      </script>

category checkboxes

  <?php
          
          
            foreach($cat as $row)
            {
                
            ?> 
           <input class = "messageCheckbox" type = "checkbox" id = "check" value = "<?php echo $row["id"]; ?>">
           <label for = "check"><?php echo $row["name"]; ?></label>
           
           
           <?php
            }
           ?>
    
    <br>
    
    <div id="txtHint"><b></b></div>

getsubcat.php

<?php
$q = intval($_GET['q']);


$result = $link->query("SELECT *
FROM subcat WHERE cat_id = '".$q."'");

?>
<div class = "checkbox">
    
<?php
while($row = mysqli_fetch_array($result)) {
    
?>

<input type="checkbox" id="sub_cat" name="sub_cat" value="<?php echo $row['subcat']; ?>">
<label for="sub_cat"> <?php echo $row['subcat'];  ?></label><br>

<?php 
}


?>

I am trying to solve with j query code attached but when I checked checkbox it displayed the subcategories of all checked checkboxes but when un check any of the box this will un display all the subcategories




Aucun commentaire:

Enregistrer un commentaire