0

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^
?>
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • What line does php error report in? Normally a full trace is sent. – user2420647 Oct 04 '15 at 18:02
  • Here's what I always recommend to people debugging. Try things individually to see if you can trace the issue. Remove certain parts of the code, by commenting, and see if that resolves the issues. – Brandon White Oct 04 '15 at 18:04
  • @BrandonWhite I would but I'm if its the Javascript incorrect or PHP. – Joshua Allen Oct 04 '15 at 18:07
  • An `Uncaught TypeError` is typically Javascript related. Also, why are you defining your function `processJson()` inside of your `.click()` event? – Brandon White Oct 04 '15 at 18:18
  • @BrandonWhite The javascript error is due to the errors not being displayed properly/defined I don't think it even submits to my unban.php file atm so nothing is done i feel when button is clicked. – Joshua Allen Oct 04 '15 at 18:23
  • @JoshuaAllen you don't echo a "required" key in your php so the javascript can't access it Edit: also, you actually use "error" in your php but try and get "errors" with an "s" in your JS –  Oct 04 '15 at 18:24
  • Add a couple `console.log("Step #");` Statements in your click event to see where it stops, then. – Brandon White Oct 04 '15 at 18:25
  • @BrandonWhite put a console.log just after function processJson(data) {} it gets to that. https://gyazo.com/b8aa8aa068f21befe35ddb5e47bdff87 Gets to Step 6 – Joshua Allen Oct 04 '15 at 18:30
  • @Terminus pointed out that I'm using error in my php but errors in javascript. Added an s to error in php and now that Uncaught Type error is gone. – Joshua Allen Oct 04 '15 at 18:34

1 Answers1

0

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
?>
Community
  • 1
  • 1
  • Thanks for your help, only issue is I get 500 error on unban.php with this error. Fatal error: Call to a member function bind_param() on boolean in C:\inetpub\wwwroot\ase\engine\post\unban.php on line 11 – Joshua Allen Oct 05 '15 at 06:07
  • @JoshuaAllen What kind of database are you using and how are you connecting to it? That error is because my code is written for a connection to a mysql database using the mysqli library. –  Oct 05 '15 at 06:10
  • I'm using MariaDB 10.0 @Terminus – Joshua Allen Oct 05 '15 at 06:16
  • @JoshuaAllen oh... you can basically ignore my answer... what is the php library that you use to connect to your db called? –  Oct 05 '15 at 06:17
  • admin_required.php If i'm understanding your question correctly. I define that on all PHP pages for query's to work. – Joshua Allen Oct 05 '15 at 06:20
  • Right but what's in there that makes the connection to the database? (What do you set $db = to? –  Oct 05 '15 at 06:21
  • $db = new MySQLi(SQL_HOST, SQL_USER, SQL_PASS, SQL_DBN, 3306); – Joshua Allen Oct 05 '15 at 06:22
  • @joshua so you are using [mysqli](http://php.net/manual/en/mysqli.construct.php)? I'll investigate further later. Sleep & work now –  Oct 05 '15 at 06:26
  • Sorry for the confusion. Thanks for the help so far. Look forward to further support later. – Joshua Allen Oct 05 '15 at 06:27
  • Have you had a chance to investigate further? – Joshua Allen Oct 06 '15 at 05:50
  • @joshua see edit. Id just left out the FROM in the delete so the statement wasn't preparing. –  Oct 06 '15 at 11:23
  • it pops up saying user was unbanned but it doesn't actually delete the user. I tried changing the insert query to "DELETE FROM users_bans WHERE id = 10" and sure enough it removed 10 but when I put it back to "DELETE FROM users_bans WHERE id = ?" it doesn't work? – Joshua Allen Oct 06 '15 at 17:35
  • I can't see any error displayed anywhere. All it does is say user was unbanned. – Joshua Allen Oct 06 '15 at 18:49
  • Is the id column in the ban_users table an int or a varchar? If it's an int, change `bind_param("s")` to `bind_param("i")`. –  Oct 06 '15 at 19:26
  • It is an int, changed that code originally before after reading the comment. So thats not the issue. – Joshua Allen Oct 06 '15 at 20:15
  • @JoshuaAllen I forgot I had that comment in there. It might not be showing the error cause of `print_r`. Try `echo json_encode(array ('message'=>$db->error));` instead. –  Oct 06 '15 at 20:31
  • Or just look at what is returned using the web developer console in your browser and looking at the xhr requests. –  Oct 06 '15 at 20:32
  • it comes up saying null. Always watch the console. {"message":null} – Joshua Allen Oct 06 '15 at 20:34
  • @JoshuaAllen I don't know what to tell you. I'd have to put my hands in the code (so to speak) to tell you more. All I can suggest is returning to your old solution of concatenation but atleast use [mysqli real eacape steing](http://php.net/manual/en/mysqli.real-escape-string.php) if you want to test til you get it to work, stick everything in var_dump statements so you can see what's going on. Definitely read more about mysqli and its error reporting in particular. Sorry I couldn't explain better. Good luck. –  Oct 07 '15 at 03:12