skip to Main Content

I’m dynamically generating <div> rows with 5 items per row using simple php while loop. Now my goal after that was to create a select form with dynamically created option‘s as options to delete the selected item.

Now I think that the issue is, that my generated options don’t interact with delete php file. I can delete the file manually using GET and typing the required string into url, but it does not work after pressing the button using POST.

Loop to create the rows:

<?php   $count = 1; 
        while($data = mysqli_fetch_array($result)) {
            if($count === 1) {
                echo "<div class='img_container'>";
            }
                echo "<div  class='img_div' id='".$data['title']."'>"; 
                    echo "<img src='uploads/" . $data['filename']."'>";
                    echo "<p delete_id='".$data['id']."'  class='img_title' >" .$data['title']. "</p>";
                    echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
                    echo "<p>" .$data['price']. "</p>";
                echo "</div>";
            if($count % 5 === 0) {
                echo "</div>";
                $count = 1;
                continue;
            }
            $count++;
        }
?>

Selection form:

<form class='flex-container' id='remove-form'>
                <p>Select and Remove Item</p>
                <select id='selectOpt' name='title'>
                    <option value="" selected disabled hidden>Choose Title</option>
                </select>
                <button id='rmvBtn' name='remove' <?php include_once 'delete.php' ?>>Delete</button>
            </form>

Delete file:

if(isset($_POST['remove'])) {
            $title = $_POST['title'];
            $pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
            $query = 'DELETE FROM photos WHERE title = :title';
            $stmt = $pdo->prepare($query);
            $stmt->bindPARAM(':title', $title);
            $stmt->execute();
        }

jQuery to generate options and ajax:

(".img_title").parent().each((i,e)=> $("#selectOpt").append("<option value='" + e.id + "'>" + e.id + "</option>"));


//Delete selected item
$(document).on('click', '#rmvBtn', function() {

    del_title = $("#"+ $("#selectOpt").val()).val();
       $.ajax({
            type: 'POST',
            url: 'delete.php',
            data: {title:del_title},
            success: function() {
                    del_title.remove();
                    $("#selectOpt option:selected").remove();
            }

        });
    })

2

Answers


  1. Chosen as BEST ANSWER

    Okay, this is actually weird, I don't know how I fixed this issue or what was wrong, but that's what I basically did to make it work:

    $(document).on('click', '#rmvBtn', function() {
        var del_title = $("#selectOpt").val();
        $.ajax({
             type: 'POST',
             url: 'delete.php',
             cache: false,
             data: {title:del_title},
             success: function(data) {
                    alert(data) /*used it to see what's the response from delete.php file*/
                    $("#"+ $("#selectOpt").val()).remove();
                    $("#selectOpt option:selected").remove();
             },
             error: function() {
                 alert('Failed');
             }
         });
     })
    

    At first I was not getting the response from the php file at all (alert was empty), so I removed the isset($_POST['remove']) completely and commented out everything and just made the file to echo 'success'. After that I was getting alert:success, then changed echo 'success' to $title = $_POST['title'] and I was getting the response I needed. After that everything just started working. I'm not really sure what was the issue, but this works just fine now.

    delete.php

    <?php    
           $title = $_POST['title'];
           $pdo = new PDO('mysql:host=localhost;dbname=second_project', 'root', '');
           $query = 'DELETE FROM photos WHERE title = :title';
           $stmt = $pdo->prepare($query);
           $stmt->bindPARAM(':title', $title);
           $stmt->execute();
    

  2. You don’t need the count. Just place the img_container outside of the while loop.

    <?php 
       $html = "";  
       $html .= "<div class='img_container'>";
       while($data = mysqli_fetch_array($result)) {
           $html .= "<div  class='img_div' id='".$data['title']."'>"; 
           $html .= "<img src='uploads/" . $data['filename']."'>";
           $html .= "<p delete_id='".$data['id']."'  class='img_title' >" .$data['title']. "</p>";
           $html .= "<p class='img_desc'>" .$data['photo_description']. "</p>";
           $html .= "<p>" .$data['price']. "</p>";
           $html .= "</div>";   
       }
       $html .= "</div>";
       echo $html;
       ?>
    

    I did an example
    HTML:

    <label for="cars">Choose a car:</label>
    
    <select name="cars" id="selectOpt">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
    <button id='rmvBtn'>Delete</button>
    

    JQuery:

    $(document).on('click', '#rmvBtn', function() {
      var del_title = $("#selectOpt").val();
      console.log(del_title);
      var json = del_title;
      jQuery.ajax({
        url: '/echo/json/', // Replace with your Url
        dataType: 'json',
        type: 'POST',
        data: {
          del_title: del_title
        },
        success: function(data) {
          console.log('del_title', del_title);
          $('#selectOpt option[value=' + del_title + ']').remove();
        }
      });
    });
    

    I did a example jsfiddle where you can play with the code:
    https://jsfiddle.net/bogatyr77/qdeL4tcp/3/

    Change this:

    <button id='rmvBtn' name='remove' <?php include_once 'delete.php' ?>>Delete</button>
    

    to

    <button id='rmvBtn' name='remove'>Delete</button>
    

    Here you have to put into your Url to the delete.php

    url: 'delete.php', // Replace with your Url
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search