0

I am writing a PHP application that returns info to a datatable with ajax and serverside being the option. I am running into a few issues mainly with searching and pagination. Currently, neither of these works although enabled and I have tried to make my own search query on the PHP side. Just getting an invalid JSON response for this. Pagination I am not sure about if I have to implement anything special for but I assume not. Pagination on my datatable currently displays that there are multiple pages but when selecting them it doesn't cycle through the data for the second page instead of still showing the data for the first, this happens on every page when selected.

My Datatable looks like this http://i.edbrook.site/brave_YhbmzijyBF.png http://i.edbrook.site/brave_kzlVgX4TnP.png

My code for the JS looks like this (for some context I am getting a value from the URL to parse through the ajax, I know this is insecure that's another thing I will do at a later time)

    $(document).ready(function(){
        // Gets All Parameters from the URL
        let searchParams = new URLSearchParams(window.location.search)

        // Tries to See if the Player Paramter is in the URL if it isnt throw a Error.
        let param = searchParams.has('player') // true
        if (!param) {
            console.error("No Player Key Entered ")
        }

        // If a Parameter does exsist.
        else {
            // Get Statistical Data
            console.log("Executed");
            // Data Table Gets information for all Events.
            var EventsData = $('#eventList').DataTable({
                "lengthChange": false,
                "processing": true,
                "serverSide": true,
                "order": [],
                "ajax": {
                    url: "action.php",
                    type: "POST",
                    data: {action: 'listevents', id: searchParams.get('player')},
                    dataType: "json"
                },
                "language": {
                    "lengthMenu": "_MENU_",
                    "search": ""
                },
                "columnDefs": [
                    {
                        "targets": [0, 1, 2, 3],
                        "orderable": true,
                    },
                ],
                "pageLength": 25
            });
            console.log(EventsData)
        }
    });

For the PHP

    public function getPlayerEvents($id) {
        $PlayerListErrorMessage = '';

        $sqlQuery = "SELECT * FROM Edbtvplays_UnturnedLog_Events WHERE PlayerId = '".$_POST["id"]."' ";

        // If there is a search request.
        if(!empty($_POST["search"]["value"])){
            $sqlQuery .= '(EventType = "'.$_POST["search"]["value"].'" ';
            $sqlQuery .= ' OR EventData LIKE "%'.$_POST["search"]["value"].'%" ';
        }

        if(!empty($_POST["order"])){
            $sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
        } else {
            $sqlQuery .= 'ORDER BY EventType DESC ';
        }


        $result = mysqli_query($this->dbConnect, $sqlQuery);

        $filterednumRows = mysqli_num_rows($result);

        // Gets the total number of rows in the database for this user as its used for datatables list.
        $totalquery = "SELECT * FROM Edbtvplays_UnturnedLog_Events WHERE PlayerId = ".$id.";" ;
        $numRows = mysqli_num_rows($result);

        $EventData = array();

        while($Event = mysqli_fetch_assoc($result) ) {
            $EventRows = array();
            $EventRows[] = $Event['EventType'];
            $EventRows[] = $Event['EventData'];
            $EventRows[] = $Event['ServerId'];
            $EventRows[] = $Event['EventTime'];
            $EventData[] = $EventRows;
        }
        // Inner join the server to get the Server name to display on the Event table.


        $output = array(
            "draw"              =>  intval($_POST["draw"]),
            "recordsTotal"      =>  $numRows,
            "recordsFiltered"   =>  $filterednumRows,
            "data"              =>  $EventData
        );

        echo json_encode($output);

    }

For Actipn.php which calls the PHP above ( i have a lot of tables and wanted to make it neat in classes)

else if(!empty($_POST['action']) && $_POST['action'] == 'listevents') {
    $players->getPlayerEvents();
}

Any help would be appreciated, thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ed Brook
  • 55
  • 2
  • 10
  • 2
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – hppycoder Mar 18 '21 at 19:33
  • 2
    Datatables is great but often requires use of the development tools on your browser. Using the Network tab you should see the AJAX call go out, and the response that comes back. I would look to see what is being returned for the draw and recordsTotal – hppycoder Mar 18 '21 at 19:37
  • @hppycoder The return looks like https://p.edbrook.site/hyhexibaqe.hs – Ed Brook Mar 18 '21 at 19:45
  • I don't see you using the `$_POST['start']` for the LIMIT, and `$_POST['length']` for the offset - helpful tutorial here shows how to use them https://makitweb.com/datatable-ajax-pagination-with-php-and-pdo/ – hppycoder Mar 18 '21 at 20:28
  • DataTables with AJAX takes the `recordsTotal` and `recordsFiltered` to figure out how many pages there should be. Then when the page is clicked it will tell you the `start` and `length` so your return can have the records for just that page. – hppycoder Mar 18 '21 at 20:29
  • @hppycoder Thanks for your help, worked like a charm! Now just a way to fix the search if you are familiar with that at all? – Ed Brook Mar 18 '21 at 23:03

0 Answers0