1

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();
            }

        });
    })
Auri-stack
  • 33
  • 6
  • Why are you including `delete.php` inside your remove button? Where do you populate the select box? It only seems to contain a single option? You also need to [prevent the form from being submitted](https://stackoverflow.com/a/53314882/2453432) normally when using Ajax, or your JS won't be executed (since the form will be submitted as a GET request and reloading the page) – M. Eriksson Aug 16 '21 at 09:03
  • the code seems to be a mix of submitting and ajax. to debug, do an alert(del_title); after asinging it (to see the value and if it is called). and in your delete.php : if(isset($_POST['remove'])) isnt set, when called by ajax, maybe do a if(isset($_POST['title'])) – FatFreddy Aug 16 '21 at 09:11
  • I've included delete just so `GET` works, because other way `GET` does not work at all. I populate my select box dynamically (you can see options in inspect) – Auri-stack Aug 16 '21 at 09:24
  • I've added the `alert` and it's probably where it does not get assigned maybe? Because it's empty (no value is shown) – Auri-stack Aug 16 '21 at 09:26
  • Okay I've changed `del_title = $("#"+ $("#selectOpt").val()).val();` to `del_title = $("#selectOpt").val();` and the value now is shown. Still deletion does not work from db. – Auri-stack Aug 16 '21 at 09:42
  • so do an print_r($_POST) before the if... in your delete.php, there should be set $_POST['title'] , but no $_POST['remove'] – FatFreddy Aug 16 '21 at 09:51
  • I tried `print_r($_POST['title'])` and there's error: `Undefined array key $title`. Not sure why though. – Auri-stack Aug 16 '21 at 09:55
  • I did a small and easy PHP Ajax example on github. Maybe this will help you: https://github.com/bmehler/AjaxExample. Could it be that you already post your Problem. I think I already answered you in another question. – Bernhard Beatus Aug 16 '21 at 10:03
  • I tried generating `option` with php instead of jQuery because I was thinking maybe that's the issue. But I get the same error, for some reason `$title` is not assigned. – Auri-stack Aug 16 '21 at 10:32

2 Answers2

0

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
Bernhard Beatus
  • 1,191
  • 1
  • 5
  • 6
  • Counter is needed because I'm doing 5 items per `div` – Auri-stack Aug 16 '21 at 12:52
  • How many items you get back from your db select statement? Maybe you can only retrieve the 5 items with limit or a where clause. – Bernhard Beatus Aug 16 '21 at 12:54
  • And also, thanks for your code, but the problem persists with the same error. Maybe I'm linking delete.php to url somehow wrongly? It sits in the main folder, so I just do : `'delete.php'` – Auri-stack Aug 16 '21 at 12:56
  • You have to do input the route to delete.php starting from your jquery script. So if the jquery is in a subfolder you have to do ../delete.php and so on. See here: https://www.w3schools.com/html/html_filepaths.asp – Bernhard Beatus Aug 16 '21 at 12:58
  • No, maybe you misunderstood me. Counter is to check whenever the row is "filled", once the counter reaches 5, I start from the beginning adding items to new `div`, and etc. Basically I want to create `divs` with 5 items per `div`. Does it make sense? – Auri-stack Aug 16 '21 at 13:00
  • Okay. So, my jQuery is in sub folder and delete.php is in the main folder, so I just do url: `../delete.php'` ? Also what about the delete.php file itself, do I need to link it somwhere or no? Because I've tried linking like this, no results yet. – Auri-stack Aug 16 '21 at 13:05
  • So do ../subfolder/delete.php. You don't have to link it anywhere else. If your are on an url oder localhost you can also do https:// or htttp:// localhost/subfolder/delete.php – Bernhard Beatus Aug 16 '21 at 13:34
  • What are you saying makes sense, but If I inspect the network tab and if I don't link the file just 'delete.php' I'm getting `404` error for xhr. At this point I don't know why it doesn't delete the item from db, because everything looks good... – Auri-stack Aug 16 '21 at 13:41
0

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();
Auri-stack
  • 33
  • 6