0

I have 2 ajax functions. The first one is for sorting data from my database (A-Z, Z-A, etc.) and the second one is for displaying the data from the database after you click a div with a specific id (if you click a div with id "pizza" it will display info for the row where name = "pizza").

Both scripts work fine separately, but when I first sort my list of divs and then try to click one of them nothing happens. When I click it without sorting everything is displayed as it should. When I sort the list and then refresh the page the content will be displayed as it should on the button click.

// head tag
<script>
$(function() {
  $('#sort_form').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
      type: "post",
      url: 'php/display.php',
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function(response) {
        $(".recipe-list").html(response);
      },
      error: function() {
      }
    });
  });
});

$(function() {
  $('.product').on('click', function(e) {
    var product = $(this).attr('id');

    $.ajax({
      type: "post",
      url: 'php/recipe-container.php',
      data: {
        "name": product
      },
      success: function(response) {
        $(".display_recipe").html(response);
      }
    });
  });
});
</script>
// HTML
<form method="POST" id="sort_form" enctype='multipart/form-data'>

  <input type="submit" id="sort_submit">
                    
  <select name="sort" id="sort" onchange="$('#sort_submit').submit()">
    <optgroup label="Alphabetically">
      <option value="alphabet"> 
        A-Z
      </option>

      <option value="alphabet_rev">
        Z-A
      </option>
    </optgroup>
                        
    <optgroup label="Whole">
      <option value="kcal_low_all">
        Kcal (to highest)
      </option>

    <option value="kcal_high_all">
      Kcal (to lowest)
      </option>
    </optgroup>
  </select>

</form>

<div class="recipe-list">
  <?php
    require "php/display.php";
  ?>
</div>

<div class="display_recipe">
</div>
// sort-list.php
<?php

$sort = isset($_POST["sort"]) ? $sort = $_POST["sort"] : "alphabet_p";
$sql = "SELECT * FROM product WHERE type = $dish_type ORDER BY name";
        
$kcal_query = "(fat * 9 + carbohydrates * 4 + fiber * 2 + protein * 4)";
$carbohydrates = "carbohydrates / 10";
$wpts_query = "(fat * 9 + protein * 4) / 100";

switch ($sort) {
    case "alphabet":
        $sql = "SELECT * FROM product WHERE type = $dish_type ORDER BY name";
    break;
                
    case "alphabet_rev":
        $sql = "SELECT * FROM product WHERE type = $dish_type ORDER BY name DESC";
    break;
 
    case "kcal_low_all":
        $sql = "SELECT * FROM product WHERE type = $dish_type ORDER BY $kcal_query";
    break;
            
    case "kcal_high_all":
        $sql = "SELECT * FROM product WHERE type = $dish_type ORDER BY $kcal_query DESC";
    break;
}

?>    
// display.php
function display_content($dish_type){
    require "sort-list.php"; 
        
    $con = mysqli_connect("localhost", "root", "", "cookbook");
    $res = mysqli_query($con,$sql);

    while($row = mysqli_fetch_assoc($res)) {
        $recipename = $row['name'];
        $fat = (int)$row['fat'];
        $carbohydrates = (int)$row['carbohydrates'];
        $fiber = (int)$row['fiber'];
        $protein = (int)$row['protein'];
        $weight = (int)$row['weight'];
        $portion = (int)$row['portion'];
            
        $kcal = ($fat * 9) + ($carbohydrates * 4) + ($fiber * 2) + ($protein * 4);
        $cp = $carbohydrates / 10; // Carbohydrate portion = 10g carbs
        $wpts = ($fat * 9 + $protein * 4) / 100; // Warsaw Pump Therapy School = (fat kcal + protein kcal) / 100
            
        echo "<p id='".$recipename."' class='product'>".$recipename."</p>";
        echo "<br>Whole:<br>";
        echo round($kcal, 1)." kcal<br>";
        echo round($cp, 1)." CP<br>";
        echo round($wpts, 1)." WPTS<br>";
    }
    mysqli_close($con);
}

function recipe_list_dishes() {
    display_content("'dishes'");
}

function recipe_list_desserts() {
    display_content("'desserts'");
}

echo    "<div class='main-module-header'>
            <h3>dishes</h3>
        </div>";
recipe_list_dishes();

echo    "<div class='main-module-header'>
            <h3>desserts</h3>
        </div>";
recipe_list_desserts();
?>
// recipe-container.php
<?php

function display(){
    $con = mysqli_connect("localhost", "root", "", "cookbook");

    $product = $_POST["name"];
    $sql = "SELECT * FROM product WHERE name = '$product'";
    $res = mysqli_query($con,$sql);

    while($row = mysqli_fetch_assoc($res)) {
        $name = $row['name'];
        $description = $row['description'];
        $date = $row['date'];
        $image = $row['image'];
        $fat = $row['fat'];

        echo $name;
        echo "<br>";
        echo $description;
        echo "<br>";
        echo $date;
        echo "<br>";
        echo $image;
        echo "<br>";
        echo $fat;
    }

mysqli_close($con);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST'){ 
    display(); 
}

?>

Note: the code above is only a fraction of the actual code. When I sort the list first and then try to click the div there is no action on the page and no action in the network tab. Is there a way to fix that?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Astw41
  • 394
  • 3
  • 12
  • In display.php, there is a list generated from the database. – Astw41 Aug 07 '22 at 20:32
  • 1
    Because your jquery event handler listening to clicks on the "product" class was bound to the list which was there when the page first loaded, the ones which existed when the event handler was declared. Your code for sorting the data removes all those and replaces them with new ones, and there is no event bound to those. I suggest you learn about delegated events in jQuery, to avoid this problem. – ADyson Aug 07 '22 at 20:33

0 Answers0