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

        });
    })
9
  • 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 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) Commented Aug 16, 2021 at 9: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'])) Commented Aug 16, 2021 at 9: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) Commented Aug 16, 2021 at 9: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) Commented Aug 16, 2021 at 9: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. Commented Aug 16, 2021 at 9:42

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

8 Comments

Counter is needed because I'm doing 5 items per div
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.
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'
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: w3schools.com/html/html_filepaths.asp
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?
|
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.