Run jquery function from all elements of foreach loop

Viewed 433

I have a table with items for each user and every table has input fields for new items.

By clicking the „Add“-button the newly entered item is sent to database and displayed in the table. This works perfekt for one table, however, not for multiple tables.

I have tried to change ids to classes in the jquery function, but then items are added to all tables and not only into the desired one.

Here is my code:

index.php

 <body>
    <div class="container">
   
<?php  
  
$usertables = array();
$usertables[] = 'user1';
$usertables[] = 'user2';
$usertables[] = 'user3';
$usertables[] = 'user4';
                            
foreach ($usertables as $value){
                            
    $query = "SELECT * FROM $value ORDER BY id ASC";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();                                               
?>    
            
        <h3><?php echo $value; ?></h3>
           
        <form method="post" id="add_details">
            <input type="hidden" name="value" value="<?= htmlspecialchars($value); ?>" />
            <div class="form-group">
                <label>Item name</label>
                <input type="text" name="item_name" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Height</label>
                <input type="text" name="item_height" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Width</label>
                <input type="text" name="item_width" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Color</label>
                <input type="text" name="item_color" class="form-control" required />
            </div>
            <div class="form-group">
                <input type="submit" name="add" id="add" class="btnn btn-success" value="Add" />
            </div>
        </form>
           
        <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>Name</th>
                <th>Height</th>
                <th>Width</th>
                <th>Color</th>
            </tr>
         </thead>
         <tbody id="table_data">
<?php
    foreach($result as $row) {
        echo '<tr>
               <td>'.$row["item_name"].'</td>
               <td>'.$row["item_height"].'</td>
               <td>'.$row["item_width"].'</td>
               <td>'.$row["item_color"].'</td>
              </tr>';
    }
?>
        </tbody>
        </table>
                
<?php                 
}   // end of foreach                
?>
              
</div>
</body>
</html>

<script>
    $(document).ready(function(){
        $('#add_details').on('submit', function(event){
            event.preventDefault();
            $.ajax({
                url:"insert.php",
                method:"POST",
                data:$(this).serialize(),
                dataType:"json",
                beforeSend:function(){
                    $('#add').attr('disabled', 'disabled');
                },
                success:function(data){
                    $('#add').attr('disabled', false);
                    if(data.item_name) {
                        var html = '<tr>';
                        html += '<td>'+data.item_name+'</td>';
                        html += '<td>'+data.item_height+'</td>';
                        html += '<td>'+data.item_width+'</td>';
                        html += '<td>'+data.item_color+'</td></tr>';
                        $('#table_data').append(html);
                        $('#add_details')[0].reset();
                    }
            }
        })
    });
});
</script>

insert.php

<?php

$connect = new PDO("mysql:host=localhost;dbname=usertables", "root", "");

//$tablename = $_GET['tablename'];
$value = $_POST["value"];
//echo $value;
$data = array(
      ':item_name'  => $_POST["item_name"],
      ':item_height'  => $_POST["item_height"],
      ':item_width'  => $_POST["item_width"],
      ':item_color'  => $_POST["item_color"],
); 

$query = "INSERT INTO $value 
                (item_name, item_height, item_width, item_color) 
        VALUES (:item_name, :item_height, :item_width, :item_color)";

$statement = $connect->prepare($query);

if($statement->execute($data)) {
    $output = array(
       'item_name' => $_POST['item_name'],
       'item_height' => $_POST['item_height'],
       'item_width' => $_POST['item_width'],
       'item_color' => $_POST['item_color'],
    );

    echo json_encode($output);
}
?>

Since I am rather new to jquery I would like to ask if there is any simple way to run the jquery-Add-function in the respective table, only?

Thank you for your help!

1 Answers

You can use $value as id of tbody for particular user table and when user click on submit button get the value of input using $(this).find("input[name=value]").val() and then use $('#' + value).append(html); to append data to tbody for particular user table only .Also, only change you need to make in your html code is adding id to tbody ie. :<tbody id="<?= htmlspecialchars($value); ?>"> .

Demo Code :

$('form').on('submit', function(event) {
  event.preventDefault();
  var $this = $(this)
  var value = $(this).find("input[name=value]").val(); //get hidden input value
  console.log(value)
  /* $.ajax({
     url: "insert.php",
     method: "POST",
     data: $(this).serialize(),
     dataType: "json",
     beforeSend: function() {
       $('#add').attr('disabled', 'disabled');
     },
     success: function(data) {
       $('#add').attr('disabled', false);
       if (data.item_name) {
         var html = '<tr>';
         html += '<td>' + data.item_name + '</td>';
         html += '<td>' + data.item_height + '</td>';
         html += '<td>' + data.item_width + '</td>';
         html += '<td>' + data.item_color + '</td></tr>';*/
  var html = "<tr><td colspan='4'>append me</td></tr>";
  $('#' + value).append(html); //append data 
  $this[0].reset();

  /* }
    }
  })*/

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="add_details">
  <input type="hidden" name="value" value="something" />
  <div class="form-group">
    <label>Item name</label>
    <input type="text" name="item_name" class="form-control" required />
  </div>
  <div class="form-group">
    <input type="submit" name="add" id="add" class="btnn btn-success" value="Add" />
  </div>
</form>

<table class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>Name</th>
      <th>Height</th>
      <th>Width</th>
      <th>Color</th>
    </tr>
  </thead>
  <tbody id="something">

  </tbody>
</table>
<form method="post" id="add_details">
  <input type="hidden" name="value" value="something1" />
  <div class="form-group">
    <label>Item name</label>
    <input type="text" name="item_name" class="form-control" required />
  </div>
  <div class="form-group">
    <input type="submit" name="add" id="add" class="btnn btn-success" value="Add" />
  </div>
</form>

<table class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>Name</th>
      <th>Height</th>
      <th>Width</th>
      <th>Color</th>
    </tr>
  </thead>
  <tbody id="something1">

  </tbody>
</table>

Related