-1

I have a select "groupsId" on my page. When I select a value in it, I have a new select "category". It all works and I get the values. But when, when selecting a category, I try to get another select "subcategory", then it does not appear and the ajax request does not pass. Tell me what to do.

Here is my js

  $('#groupId').change(function(e) {
    //Grab the chosen value on first select list change
    var selectval = $(this).val();

    if (selectval == "") {
        //Display initial prompt in target select if blank value selected
            $('#CategorySelect').html("");
    } else {
      //Make AJAX request, using the selected value as the GET
      $.ajax({url: './include/ajax/CategoryOption.php?cvalue='+selectval,
             success: function(output) {
                //alert(output);
                $('#CategorySelect').html(output);
            },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status + " "+ thrownError);
          }});
        }
    });

  $('#categoryId').change(function(e) {
    //Grab the chosen value on first select list change
    var selectvalue = $(this).val();

    if (selectvalue == "") {
        //Display initial prompt in target select if blank value selected
            $('#subCategorySelect').html("");
    } else {
      //Make AJAX request, using the selected value as the GET
      $.ajax({url: './include/ajax/SubCategoryOption.php?svalue='+selectvalue,
             success: function(output) {
                //alert(output);
                $('#subCategorySelect').html(output);
            },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status + " "+ thrownError);
          }});
        }
    });

index.php

         <form class="form-horizontal" method="POST" enctype="multipart/form-data"
                <div class="form-group">
                    <label for="group" class="col-sm-2 control-label">Departments:</label>
                    <div class="col-sm-10">
                        <select class="form-control" id="groupId" name="groupId">  
                        <?php department::DepartmentsList(); ?> 
                        </select>
                    </div>
                </div>
                <div id="CategorySelect"></div>
                <div id="subCategorySelect"></div>
         </form>

CategoryOption.php

<?php

$mysqli = dbConnect();

$selectval =  $_GET['cvalue'];

if (!is_numeric($selectval)){
    echo "Invalid Data";
    exit;
}

$sql = "select сt.name as categorynames,
        g.name as groupname,
        g.id as categoryid,
        сt.id as groupid
    from categories сt, groups g
        where сt.groupid = g.id
        and сt.groupid = $selectval";
$result = $mysqli->query($sql);

$mysqli->close();

if ($result->num_rows > 0) {
    // output data of each row
     echo '<div class="form-group">
                    <label for="category" class="col-sm-2 control-label">Категория</label>
                    <div class="col-sm-10">
            <select class="form-control" id="categoryId" name="categoryId">
                <option>Select category</option>';

    while($row = $result->fetch_assoc()) {
        echo '<option value="'.$row['categoryid'].'">' .$row['categorynames']. '</option>';
    }
    echo '</select>
        </div>
        </div>';
} else {
    
}
?>
  • `#categoryId` doesn't exist in your markup? – Teemu May 27 '21 at 09:50
  • It is drawn with php in CategoryOption.php – sadsadsadsad May 27 '21 at 09:55
  • Yes, but at the time you attach the events the said element doesn't exist. See https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Teemu May 27 '21 at 09:57
  • The block with categories appears and works, but after selecting the desired category in it, the block with subcategories that correspond to this category does not appear. – sadsadsadsad May 27 '21 at 10:03
  • You can't attach a listener to an element which doesn't exist. Please re-read my previous comment. – Teemu May 27 '21 at 10:04
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 27 '21 at 10:10

1 Answers1

0

I don’t know how correct it is, but when I did it like this, everything worked as I wanted.

$('#dashboard').addClass("active");

$(document).ready(function($) {

  $('#groupId').change(function(e) {
    //Grab the chosen value on first select list change
    var selectval = $(this).val();

    if (selectval == "") {
        //Display initial prompt in target select if blank value selected
            $('#CategorySelect').html("");
            $('#subCategorySelect').html("");
    } else {
      //Make AJAX request, using the selected value as the GET
      sel_1 = new $.ajax({url: './include/ajax/getCategoryOption.php?cvalue='+selectval,
             success: function(output) {
                //alert(output);
                $('#CategorySelect').html(output);
                  $('#categoryId').change(function(e) {
                    //Grab the chosen value on first select list change
                    var selectvalue = $(this).val();

                    if (selectvalue == "") {
                        //Display initial prompt in target select if blank value selected
                            $('#subCategorySelect').html("");
                    } else {
                      //Make AJAX request, using the selected value as the GET
                      sel_2 = new $.ajax({url: './include/ajax/getSubCategoryOption.php?svalue='+selectvalue,
                             success: function(output) {
                                //alert(output);
                                $('#subCategorySelect').html(output);
                            },
                          error: function (xhr, ajaxOptions, thrownError) {
                            alert(xhr.status + " "+ thrownError);
                          }});
                          sel_2;
        }
    });
            },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status + " "+ thrownError);
          }});
          sel_1;
        }
    });