Roland
Roland

Reputation: 9731

Delete Entry From MySQL Table Using AJAX

As I said in another question in here, I'm creating a login class, but I'm making some additional options for it.

One of which is deleting users. I'll show you the code I'm using to do this.

First I list all the users using this function :

public function listUsers() {
    $sql = "SELECT username FROM user";
    if($stmt = $this->conn->prepare($sql)) {
        $stmt->bind_result($usrn);
        $stmt->execute();

        while ($row = $stmt->fetch()) {
            $stmt->bind_result($usrn);
            echo    '<form name="delete-user" id="'.$usrn.'" class="delete-user" method="post" action="#">'.
                        '<fieldset class="user-wrapper">'.
                            '<label for="user" class="user-label">User</label>'.
                            '<input type="text" name="user" class="user" value="'.$usrn.'" autocomplete="off" readonly="readonly" />'.
                        '</fieldset>'.
                        '<fieldset class="delete-wrapper">'.
                            '<button type="submit" name="delete" class="delete">Delete</button>'.
                        '</fieldset>'.
                    '</form>';
        }
        $stmt->close();
        echo '<div class="message-handling"></div>';
    }
        else {
            $error = true;
            $message['error'] = true;
            $message['message'] = "The Users Could Not Be Listed";
            return json_encode($message);       
        }
}

As you can see the result of this function in the HTML will be like this:

<form name="delete-user" id="altceva" class="delete-user" method="post" action="#"> 
    <fieldset class="user-wrapper">
        <label for="user" class="user-label">User</label>
        <input type="text" name="user" class="user" value="altceva" autocomplete="off" readonly="readonly" />
    </fieldset>
    <fieldset class="delete-wrapper">
        <button type="submit" name="delete" class="delete">Delete</button>
    </fieldset>
</form>

The id of the form is actually the name of each user (for each user a form is created with the user's id). Also the value of the input has the user name too, because I need it to pass it to another function so I can delete that user.

Next I'm trying to use AJAX to delete the user I want to delete. I have this function so far:

var ids = $('.delete-user-content form[id]').map(function(){
    return this.id;
}).get();

jQuery.each(ids, function() {
    console.log("#" + this + ' .delete');

    $("#" + this + ' .delete').click(function() {

    $('.delete-user-content .message-handling').fadeOut();

    $.ajax({
        type: 'POST',
        url: 'assets/class/login/process.php',
        dataType: 'json',
        data: {
            delusername:    $('.delete-user input.user').val()
        },
        success:function(data) {
            if(data.error === true) {
                $('.delete-user-content .message-handling').text(data.message).fadeIn();
                console.log(data.message);
                setTimeout(function () {
                    $('.delete-user-content .message-handling').fadeOut();
                }, 15000);
            }
                else {
                    $('.delete-user-content .message-handling').text(data.message).fadeIn();
                    console.log(data.message);
                    $('#'+id).fadeOut();
                    array.splice(index, 1);
                    setTimeout(function () {
                        $('.delete-user-content .message-handling').fadeOut();
                    }, 15000);
                }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown) {
            $('.delete-user-content .message-handling').text('Error | Check PHP log for information').fadeIn();
            console.log('Error | Check PHP log for information');
        }
    });
    return false;

});
});

And the PHP function to process the action is this one:

public function deleteUser($user) {
    $sql = "DELETE FROM user WHERE username = '$user'";
    if($stmt = $this->conn->prepare($sql)) {
        $stmt->execute();
        $stmt->close();
        $error = false;
        $message['error'] = false;
        $message['message'] = "The User ".$user." Has Been Deleted";
        return json_encode($message);
    }
        else {
            $error = true;
            $message['error'] = true;
            $message['message'] = "The User Could Not Be Deleted";
            return json_encode($message);       
        }
}

But the thing is that this doesn't work properly. One problem would be if I delete the last listed user it will actually delete the first user. Then after I make one delete, if I click on another delete nothing else will be deleted, it will just tell me that the same user as the first time was deleted.

Now, I know this is a lot of code and it's hard to understand it, but could someone help me out with it?

Upvotes: 1

Views: 929

Answers (1)

jeroen
jeroen

Reputation: 91792

It seems you are using a very complicated way to determine your user ID. Why don't you just add a hidden field to the form and attach the event handler to the form? That would eliminate the need for the map and each, speeding everything up in the process.

So you form would be something like:

<form name="delete-user" class="delete-user" method="post" action="#"> 
  <input type="hidden" name="user_id" value="PHP_ECHO_USER_ID" />
  <fieldset class="user-wrapper">
  ...

And your jquery would be simplified to:

$("form.delete_user").submit(function() {
  var user_id = $(this).find('[name="user_id"]').val();    // on the top of my head, untested...
  console.log(user_id);     // make sure you get the right user ID before doing anything else
  ...
  return false;
});

Upvotes: 2

Related Questions