skip to Main Content

I am Creating a dependency drop downs but,

When I pass Id from one function to another its not Working
here is some sample of code

<?php
include("includes/db.php");
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
     <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div>
    <select id="all_category">
        <option>select a category</option>
    </select>
</div>
<script type="text/javascript">
    $(document).ready(function(){
        category();
         function category(){
            $.ajax({
            url : "action.php",
            method : "POST",
            data : {category:1},
            success : function(data){
                $("#all_category").html(data)
            }
        })
    }
    $("#all_category").change(function () {
        var val = $(this).val();
        var xyz = $("#all_category option:selected").val();
        console.log("hello"+xyz)
    })
    })
</script>
</body>
</html>

This code is to take data from API,

And when I print the ID from first dropdown,

It just print the massage before My Id Variable in console.log

<?php
include "../db.php";
if (isset($_POST["category"])) {
    $get_assign_course = "SELECT * FROM categories";
    $run_p_cats = mysqli_query($con,$get_assign_course);
    while ($rows=mysqli_fetch_array($run_p_cats)) {
        $cat_id  = $rows['cat_id '];
        $cat_title = $rows['cat_title'];
        echo "<option value='$cat_id '>$cat_title</option>
        ";}}
?>

This is my API
help?

2

Answers


  1. Try to change this:
    $("#all_category").change(function
    Into this:

    $("#all_category").on('change',function
    

    Or try this:

    $(document).on('change','#all_category',function(){
    

    Let me know if this works for you

    Login or Signup to reply.
  2. When you use .html() in jQuery it will destroy any of the binding that has already occurred on the events. That’s because html removes the DOM tree and reinitializes it with the data.

    <script type="text/javascript">
      $(function() {
        $.ajax({
          url: "action.php",
          method: "POST",
          data: {category: 1},
          success: function (data) {
            $("#all_category").html(data);
            $("#all_category").on('change', function (evt) {
              console.log($(this).val())
            })
          }
        });
      });
    </script>
    

    To fix this issue you need to rebind after the .html() call is made.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search