0

I'm trying to remove content with jQuery/ajax which is dynamically added with a simple PHP loop, but it does not work. I'm using dynamically created <select> option to select the item and remove it by pressing the button. This is what I came up until now:

jQuery:

$(document).on('click', '#rmvBtn', function() {
    // remove the related element
    let del_title = $("#" + $("#selectOpt").val());
        $.ajax({
            type: 'POST',
            cache: false,
            processData: false,
            url: 'delete.php',
            data: {title:del_title},
            success: function(data) {
                if(data) {
                    del_title.remove();
                }
            }
        });
})

PHP delete:

    define("DB_SERVER", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_NAME", "project");

    $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
    if($mysqli->connect_error) {
        echo "Sorry, there's a problem with the website.\n";
        echo 'Error: ' . $mysqli->connect_error . '\n';
        exit();
    }
    if($_POST['title']) {
        $title = mysqli_real_escape_string($_POST['title']);
        $sql = "DELETE FROM photos WHERE title = $title";
        mysqli_query($sql);
    }

HTML Form to remove Item:

<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> /*default value*/
          /*here appear the dynamically created options*/
     </select>
     <button id='rmvBtn'>Delete</button>
</form>
NcXNaV
  • 1,657
  • 4
  • 14
  • 23
Auri-stack
  • 33
  • 6
  • If `title` is a string then your query isn't properly quoted. As is, your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. Always use [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) with [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). See [**this page**](https://phptherightway.com/#databases) and [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for some good examples. – Alex Howansky Aug 12 '21 at 14:20
  • Well Im using this just to learn so I was not thinking about injections, but thank you for informing me – Auri-stack Aug 12 '21 at 14:22
  • Hello, Welcome to SO! Please take the [tour](https://stackoverflow.com/tour), read the [help center](https://stackoverflow.com/help), and [how-to-ask](https://stackoverflow.com/help/how-to-ask) page. Your problem might caused by `title:del_title`, del_title is not a valid value, your `php delete` does not delete the item from database. So when the page refreshes, the item reappears. – NcXNaV Aug 12 '21 at 16:40
  • Well it just what I came up with by looking up examples, so I'm not really sure how to change it,since i need ```$("#" + $("#selectOpt").val())``` to get selected item – Auri-stack Aug 12 '21 at 16:54
  • Use `title:del_title.val()` instead – NcXNaV Aug 13 '21 at 09:15
  • I've played around with the code and I still don't understand why I can't delete item from the DB. I used `return: false` statement after ajax call so it doesn't refresh the page, I get `xhr` response `200 OK`. So maybe there's some problem I dont get it with delete.php ? – Auri-stack Aug 13 '21 at 10:43
  • Have you tried using `data:{title:del_title.val()}`? You're passing del_title variable to data, which contains an element not the value. – NcXNaV Aug 13 '21 at 12:41
  • Your problem could be so simple than editing java or php , check file permission, php file need to be executable by apache sever user “ in case you use apache “ also you need to add error message on php side , so you need to recheck the item after deletion to confirm the process success – Creative87 Aug 13 '21 at 14:08

2 Answers2

2

I created this little example.

$(document).on('click', '#rmvBtn', function() {
  var del_title = $("#selectOpt").val();
  console.log(del_title);
  // Your Ajax Call
  //$.ajax({
  //    type: 'POST',
  //    cache: false,
  //    processData: false,
  //    url: 'delete.php',
  //    data: {title:del_title},
  // You don't need data because you don't have a return 
  //    success: function() {
           $('#selectOpt option[value=' + del_title + ']').remove();
  //    }
  //});

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Bernhard Beatus
  • 1,191
  • 1
  • 5
  • 6
  • Well that is the thing, it should work on DOM elements for me(I had tried similar stuff) but it automatically refreshes the page and the element re-appears. Thats why I think I need to delete data from DB – Auri-stack Aug 12 '21 at 15:09
  • Oh I missed that this is within Ajax (sorry), going to try later – Auri-stack Aug 12 '21 at 15:15
  • I had tried your solution, but the problem is the same: item is removed and then the page refreshes and re-appears. – Auri-stack Aug 12 '21 at 16:09
  • Maybe my github example could help you: https://github.com/bmehler/AjaxExample It's a simple Ajax Example. – Bernhard Beatus Aug 12 '21 at 16:17
  • I'm really not sure what I'm doing wrong. I imagine it has to do with my `delete.php` - it does not receive or does not delete the data properly, but I don't know where is the issue – Auri-stack Aug 13 '21 at 08:22
  • do you get an connection error. You have a message in your delete.php. Do a print_r($_POST['title']) to see if there is a value in your variable. – Bernhard Beatus Aug 13 '21 at 12:39
1

I've edited your code and add echo to send success/failed message back to Ajax as debugging purposes. I've changed data: {title:del_title} to data: {title:del_title.val()}. I've also noticed syntax error in your php code: if($_POST['title']) { }). There shouldn't be a ) at the end of if statement.

jQuery:

$(document).on('click', '#rmvBtn', function() {
    // remove the related element
    let del_title = $("#" + $("#selectOpt").val());
        $.ajax({
            type: 'POST',
            cache: false,
            processData: false,
            url: 'delete.php',
            dataType: "json",
            data: {title:del_title.val()},
            success: function(data) {
                if(data.msg == 'Success') {
                    alert(data.msg);
                    del_title.remove();
                }
                else{
                    alert(data.msg);
                }
            }
        });
})

PHP delete:

<?php
    define("DB_SERVER", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_NAME", "project");

    $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
    if($mysqli->connect_error) {
        //echo "Sorry, there's a problem with the website.\n";
        //echo 'Error: ' . $mysqli->connect_error . '\n';
        //exit();
        $arr = ('msg' => 'mysqli Connection Error!');
    }
    if($_POST['title']) {
        $title = mysqli_real_escape_string($_POST['title']);
        $sql = "DELETE FROM photos WHERE title = $title";
        mysqli_query($sql);
        //If delete success
        if (mysqli_query($sql)){
            $arr = ('msg' => 'Success');
        }
        else $arr = ('msg' => 'Delete Item Failed');
    }
    echo json_encode($arr);
?>

html form to remove the items:

<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> /*default value*/
          /*here appear the dynamically created options*/
     </select>
     <button id='rmvBtn'>Delete</button>
</form>

I'd also recommend handling MySQL Errors when using Ajax, refer to this answer.

NcXNaV
  • 1,657
  • 4
  • 14
  • 23
  • I'm now even more confused: I've tried your solution, but what I get is this: item is not removed from the DOM before page reloads, but I get ```xhr 200 OK``` (and I can spam the remove button to get the same message). And also: item remains in the db. – Auri-stack Aug 13 '21 at 13:11
  • Yes I got that long ago, that the item is not deleted from the DOM after refresh because it's still in the db. But that's the thing, why can't I delete it from db? For example: could it be my loop to upload the files that messes up things? I'm asking since I'm walking in circles. – Auri-stack Aug 13 '21 at 13:20
  • I don't see any upload anywhere in the code. But I don't it's the problem – NcXNaV Aug 13 '21 at 13:23
  • Yea I know that you don't see it here, but I was just guessing (it's a simple while loop to echo 5 items per ```
    ```, with a counter to add additional ```
    ``` after 5 items are added)
    – Auri-stack Aug 13 '21 at 13:26
  • Now another question: the ```echo $arr``` should give me a message yes? Because I cannot see it anywhere (maybe I don't know where to look). – Auri-stack Aug 13 '21 at 13:29
  • Yes it's true, it should alert the message. Actually It should be `echo json_encode($arr)`. – NcXNaV Aug 13 '21 at 14:01