Home > Net >  removing users from page on button click using ajax technology
removing users from page on button click using ajax technology

Time:08-08

I want to remove the whole element on button click.
Removal must be done through Ajax technology, that is, without reloading the page. After deleting a user, the entry with him should disappear from the list of all users.

Here is the structure of my code:

<?php
    require_once "lib/mysql.php"; //database connection
    $query = $pdo->prepare('SELECT * FROM `users`');
    $query->execute();
    $users = $query->fetchAll(PDO::FETCH_ASSOC);
    foreach($users as $user) {
        echo '<div ><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].');">Delete</button></div>';
    }; //display all users

?>

<script>
    function deleteUser(id) {
        $.ajax({
            url: 'ajax/deleteUser.php',
            type: 'POST',
            cache: false,
            data: {'id': id},
            success: function(data) {
                $(this).closest(".infoAllUsers").remove();
            }
        });
    }
</script>

There are no errors in js and php, there is nothing in the console, deletion from the database occurs correctly.
I am new to jQuery so I have tried some things like:

$(this).parent('div').remove();
$(this).closest('div').remove();
$(this).parent('.infoAllUsers').remove();

CodePudding user response:

The code seems correct, the only thing that occurs to me is that your php backend is not returning an Http code that is in the 2XX range and that is why it does not enter the success function of your ajax request, have you tried to make a console.log () inside the function that deletes the to see if the JS reaches that point? Jquery.ajax() function documentation

CodePudding user response:

Take a different/cleaner approach

Set the id as a data attribute and assign a class, then add the click event to that.

<button data-id="'.$user['id'].'">Delete</button>

$('.infoAllUsers .delete').click(function(elm) {
  $.ajax({
    url: 'ajax/deleteUser.php',
    type: 'POST',
    cache: false,
    data: {
      'id': $(elm).data('id')
    },
    success: function() {
      $(elm).parent().remove();
    }
  });
})
  • Related