skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search