简体   繁体   中英

PHP Delete from javascript button click

I'm currently doing a PHP page that displays bans and also gives an option to unban users. I can't seem to get the button to work and run the query to unban. Any help would be much appricated.

It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get

Uncaught TypeError: Cannot read property 'required' of undefined

Here is the function listed in lightcms.php for banlist.php;

function banListAll() {
    global $db;
    $getBanListAllQuery = "SELECT * FROM users_bans";
    $getBanListAll = $db->query($getBanListAllQuery);
    while ($showBanListAll = $getBanListAll->fetch_assoc()) {   
        echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
        echo "<td>";
        echo $showBanListAll['id'];
        echo "</td>";       
        echo "<td>";        
        echo $showBanListAll['added_date'];     
        echo "</td>";               
        echo "<td>";        
        echo $showBanListAll['value'];      
        echo "</td>";       
        echo "<td>";        
        echo $showBanListAll['reason'];     
        echo "</td>";       
        echo "<td>";        
        echo $showBanListAll['expire'];     
        echo "</td>";       
        echo "<td>";        
        echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";      
        echo "</td>";       
        echo "</tr>";       
    }

}

Here is the javascript on banlist.php

<script type="text/javascript">
$(".btn-unban").click(function(){
    var articleId = "#banID"+ $(this).attr("data-id");
    var myData = "unban="+ $(this).attr("data-id"); //post variables

    var formData = new FormData(this);
    $.ajax({
        type: "POST",
        url: "./engine/post/unban.php",
        dataType:"json",
        data: myData,
        success: processJson
    });

    function processJson(data) { 

        // here we will handle errors and validation messages
        if (!data.success) {

            if (data.errors.required) {
                new PNotify({
                    title: 'Uh oh!',
                    text: data.errors.required,
                    type: 'error'
                });
            }

        } else {

            new PNotify({
                title: 'Success!',
                text: data.message,
                type: 'success'
            });
            $(articleId).fadeOut("slow");

        }
    }
});

</script>

And here is the unban.php file

<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";

$id = $_POST['id'];


$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query


if($db->query($insert)) {
    echo '{"success":true,"message":"User was unbanned!"}';
} else {
    echo '{"error":true,"message":"Sorry this has not worked, try another     time!"}';
}

//Need to work on displaying the error^
?>

Your JS looks for "errors.required" but your PHP sends "error" with no required.

Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc() ) Please consider atlest the change to unban.php as what you currently have is open to sql injection

Your new banListAll function:

function banListAll() {
    global $db;
    // don't use SELECT * if you can help it. Specify the columns
    $getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
    $getBanListAll = $db->query($getBanListAllQuery);

    while ($showBanListAll = $getBanListAll->fetch_assoc()) {
        $showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
        // array_slice to get ignore the ['id']
        echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";    
    }
}

New JS on banlist.php

<script type="text/javascript">
function processJson(data) {
    // here we will handle errors and validation messages
    if (data.error === false) {
        row.fadeOut("slow");
    }
    // assuming we always get a "message"
    new PNotify({
        title : 'Uh oh!',
        text : data.message,
        type : 'error'
    });
}

$(".btn-unban").click(function() {
    var $this = $(this); // creating jQuery objects can be costly. save some time
    var row = $this.closest('tr');
    var banID = row.data('banid');
    var postData = { unban: banID };

    var formData = new FormData(this);
    $.ajax({
        type : "POST",
        url : "./engine/post/unban.php",
        dataType : "json",
        data : postData,
        success : processJson
    });
});

</script>

And here is the unban.php file

<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";

$id = $_POST['id'];

// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);

if($deleteStmt->execute()) {
    echo jsonResult(false,"User was unbanned!");
} else {
    echo jsonResult(true,"Sorry this has not worked, try another     time!");
}

// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
    return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}

and just in case you thought unban.php was getting unnecessarily long, here it is without comments

<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";

$id = $_POST['id'];

$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
    $deleteStmt->bind_param("i",$id);

    if($deleteStmt->execute()) {
        echo jsonResult(false,"User was unbanned!");
    } else {
        echo jsonResult(true,"Sorry this has not worked, try another     time!");
    }
}
else {
    print_r($db->error);
}
// the function should go into your general functions file
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM